How to generate numbers between[-1 0] in for loop for half iterations and for other iterations it goes from [0 -1]

2 views (last 30 days)
if I am using "for loop" and for that I want to generate numbers that are in ascending order between [-1 0] then after half of my iterations I want to go back from 0 to -1 then what will be it's command?

Answers (2)

Geoff Hayes
Geoff Hayes on 18 Aug 2014
Edited: Geoff Hayes on 18 Aug 2014
Sara - just use the sort function
numIters = 50;
numToGen = 100;
for k=1:numIters
% generate your random numbers between -1 and 0
numbers = -1*rand(numToGen,1);
if k<numIters
% sort the data in ascending order
numbers = sort(numbers,'ascend');
else
% sort the data in descending order
numbers = sort(numbers,'descend');
end
end
Try the above and see what happens!

Vitali Avagyan
Vitali Avagyan on 18 Aug 2014
Edited: Vitali Avagyan on 26 Aug 2014
Geoff, I don't think your code does what Sara asked for,
Sara, it looks like from your message that you are looking for the following code:
Iters = 10;%put any number of iterations you want
numbers=zeros(1,Iters);
asc=zeros(1,floor(Iters/2));
desc=zeros(1,ceil(Iters/2));
for k=1:Iters
for k=1:floor(Iters/2);
asc(k)=-1*rand;
numbers_ascend=sort(asc,'ascend');
end
for k=1:ceil((Iters/2));
desc(k)=-1*rand;
numbers_descend=sort(desc,'descend');
end
end
numbers=[numbers_ascend numbers_descend]
Let me know if that works for you!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!