Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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?

Risposte (2)

Geoff Hayes
Geoff Hayes il 18 Ago 2014
Modificato: Geoff Hayes il 18 Ago 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 il 18 Ago 2014
Modificato: Vitali Avagyan il 26 Ago 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!

Translated by