how to do constraints for generate random numbers?
3 views (last 30 days)
Show older comments
Hello, I want to generate x random numbers from 1 to 8760 hours with the constraints x1<x2<x3 and x3 is greater or equal than 8760. I wrote the programming like below but it does not work. Thank you.
clear; clc;
count=1; kira=1;
while count <= 30; % maximum of 100 random numbers will be generated
% the following program is used to generate 20 random numbers 1 at a time
% everytime a random number is generated,fitness will be calculated
% if there is a constraint (fitness cannot be calculated), new random
% number will be generated
while kira <= 20; % 20 populations are required during initialization
x1=rand(20,1)*8759+1; % generate number from 1 to 8760
x1=round(x1);
x2=rand(20,1)*8759+1;
x2=round(x2);
x3=rand(20,1)*8759+1;
x3=round(x3);
count;
if x1<x2<x3 & x3<=8760;
kira = [x1 x2 x3]
else
count=count+1;
if kira == 21
return
end
end
end
end
3 Comments
Guillaume
on 14 Apr 2015
I don't understand why you can't generate 3 random integers within your range and then sort them to ensure they are in the right order. Why discard them if they're not in the order you want?
Answers (2)
John D'Errico
on 14 Apr 2015
I'll assume that your goal is merely to generate 3 random numbers from the interval [1,8760], such that all three of them are in increasing order.
The statement that x3 is <= 8760 is irrelevant. We already know that x3 lies in the closed interval [1,8760], so that is implicit in the first statement.
The following single statement does what you appear to be asking for.
A = sort(rand(20,3)*8759 + 1,2);
Having said that, the requirement that they lie in the interval [1,8760] suggests that very possibly your response will be that they must be integers. I know, I should have been able to read your mind. You did round them after all in the snippet of code you wrote. So to generate integers instead, just use randi instead of rand.
A = sort(randi([1,8760],20,3),2);
Next, you will probably return and say, that oh, you need them to be sampled without replacement, so that no replicates are allowed. If that is what you need, then you should say that in the first place. Or if x3 really was going to be forced to 8760 all the time, then you should have said so.
3 Comments
Guillaume
on 22 Apr 2015
what I want is the number of x1 is not greater than x2 and x3 for the whole output. Hope you can hep me. Thank you
Then why can't you just generate 20x3 = 60 numbers sort them and reshape in three columns?
A = reshape(sort(randi([1 8760], 1, 20*3)), 20, 3)
If you want to then reorder the rows randomly:
A = A(randperm(size(A, 1)), :)
If that's not what you want, then you need to explain yourself much better.
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!