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

1 次查看(过去 30 天)
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?

回答(2 个)

Geoff Hayes
Geoff Hayes 2014-8-18
编辑:Geoff Hayes 2014-8-18
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 2014-8-18
编辑:Vitali Avagyan 2014-8-26
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!

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by