使用Matlab在区间中生成随机数的步骤与实例

如何使用matlab语言在特定区间中生成随机数?

熟悉matlab语言的都知道使用rand函数可以生成0~1之间的随机数。

如何在特定区间生成随机数呢?

1.实施步骤

对于区间[A,B]中生成随机数,只需进行转换:

(1)计算区间的长度:Len=B-A;

(2)任意生成的数:X=A+Len×C。

其中:C为利用rand函数生成的0~1之间的随机数。

2.应用实例

有四组数,第一组数据30.9-31; 第二组数据33-34; 第三组数据48.5-49.8, 第四组数据38.7-39.8。

要求在每组数区间中随机生成30个数,并计算均值、方差。

代码如下:

clc;clear;close all

lower_set=[30.9,33,48.5,38.7]; %四组数下限组成的矩阵,按照顺序排列

up_set=[31,34,49.8,39.8];        %四组数上限组成的矩阵,按照顺序排列

%生成第一组随机数

rng(0)

a1=lower_set(1)+(up_set(1)-lower_set(1))*rand(1,30);

a2=lower_set(2)+(up_set(2)-lower_set(2))*rand(1,30);

a3=lower_set(3)+(up_set(3)-lower_set(3))*rand(1,30);

a4=lower_set(4)+(up_set(4)-lower_set(4))*rand(1,30);





for i=1:1:4

display("第" + string(i)+"组平均值")

switch i

case 1

mean(a1)

case 2

mean(a2)

case 3

mean(a3)

case 4

mean(a4)

end

display("第" + string(i)+"组方差")

switch i

case 1

std(a1)

case 2

std(a2)

case 3

std(a3)

case 4

std(a4)

end

end



figure

plot(a1,LineWidth=1,Color='r')

hold on

plot(a2,LineWidth=1,Color='g')

hold on

plot(a3,LineWidth=1,Color='b')

hold on

plot(a4,LineWidth=1,Color='k')

xlabel('序号')

ylabel('数值')

legend('第1组','第2组','第3组','第4组')

set(gca,"FontSize",16) %设置字体大小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值