How to generate random numbers with constraint?
조회 수: 10 (최근 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!