How to generate random numbers with constraint?
11 ビュー (過去 30 日間)
古いコメントを表示
I need ideas how to generate random numbers in given range in example under...constraint is--->1st number has to be greater than 2nd, 2nd greater than 3rd...24th greater than 25th
for n = 1 : 25
a(n) = (1.2-0.05)*rand(1)+0.05;
end
0 件のコメント
採用された回答
Torsten
2022 年 4 月 27 日
a = (1.2-0.05)*rand(25,1)+0.05;
a = sort(a,'descend')
その他の回答 (3 件)
Steven Lord
2022 年 4 月 27 日
編集済み: Steven Lord
2022 年 4 月 27 日
Generate the numbers then call sort on the array.
By the way, you don't need to use a for loop here. The rand function can generate a vector of values with a single call.
a = (1.2-0.05)*rand(1, 25)+0.05
b = sort(a, 'descend')
Prakash S R
2022 年 4 月 27 日
If all you want is that the numbers are randomly drawn from the uniform distribution between 0.05 and 1.2, you could generate a as above, follwed by
a = sort(a, 'descend')
or simply
a = sort((1.2-0.05)*rand(1,25)+0.05, 'descend');
Walter Roberson
2022 年 4 月 28 日
First branch consists of following numbers 1>2>3>4>5>6>7>8>9>10>11>12, second brach starts at number 3 of first branch and consist folloving numbers 3>13>14>15>16>17, third branch starts at number 7 of first branch 7>18>19>20>21>22 and fourth branch starts at number 9 of first branch 9>23>24>25.
format long g
rmin = 0.05;
rmax = 1.2;
UB = { [], %1 < nothing
[1] %2 < 1
[1:2] %3 < 1,2
[1:3] %4 < 1,2,3
[1:4] %5 < 1,2,3,4
[1:5] %6 < 1,2,3,4,5
[1:6] %7 < 1,2,3,4,5,6
[1:7] %8 < 1,2,3,4,5,6,7
[1:8] %9 < 1,2,3,4,5,6,7,8
[1:9] %10 < 1,2,3,4,5,6,7,8,9
[1:10] %11 < 1,2,3,4,5,6,7,8,9,10
[1:11] %12 < 1,2,3,4,5,6,7,8,9,10,11
[3] %13 < 3
[3 13] %14 < 3,13
[3 13:14] %15 < 3,13,14
[3 13:15] %16 < 3,13,14,15
[3 13:16] %17 < 3,13,14,15,16
[7] %18 < 7
[7 18] %19 < 7,18
[7 18:19] %20 < 7,18,19
[7 18:20] %21 < 7,18,19,20
[7 18:21] %22 < 7,18,19,20,21
[9] %23 < 9
[9 23] %24 < 9,23
[9 23:24] %25 < 9,23,24
};
NV = numel(UB);
V = zeros(NV,1);
V(1) = RR(rmin,rmax);
for K = 2 : NV
least = min(V(UB{K}));
V(K) = RR(rmin,least);
end
[[1:11].', V(1:11)]
[[3,13:17].', V([3,13:17])]
[[7,18:22].', V([7,18:22])]
[[9,23:25].', V([9,23:25])]
function x = RR(rmin, rmax)
x = rand() * (rmax - rmin) + rmin;
end
1 件のコメント
Walter Roberson
2022 年 4 月 28 日
Notice how near the end, everything gets squashed into very close to the lower bound. This is to be expected for this kind of generating.
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!