How to generate random numbers with constraint?
9 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Torsten
on 27 Apr 2022
a = (1.2-0.05)*rand(25,1)+0.05;
a = sort(a,'descend')
More Answers (3)
Steven Lord
on 27 Apr 2022
Edited: Steven Lord
on 27 Apr 2022
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
on 27 Apr 2022
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
on 28 Apr 2022
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 Comment
Walter Roberson
on 28 Apr 2022
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.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!