Why does my vector turn into a single number in a FOR loop
Show older comments
Im working on a school project where we are supposed to make a vector with 50 elements between 1 and 100, and then make a vector "small" containing the elements under 50 and a vector "big" with the elements over 50. The code ive been trying is:
for x=randi(100,1,50)
if x<=50
small=x;
else
big=x;
end
end
but when i run the code all the variables becomes single number
Answers (2)
madhan ravi
on 29 Oct 2018
Edited: madhan ravi
on 30 Oct 2018
But it is not efficient use loops , better to use logical indexing instead as mentioned above
x=randi(100,1,50)
for i = 1:numel(x)
if x(i)<=50
small(i)=x(i);
else
big(i)=x(i);
end
end
7 Comments
madhan ravi
on 29 Oct 2018
you should put i as an index number in order to prevent overwriting read more about loops and indexing
madhan ravi
on 29 Oct 2018
use nonzeros(small) and nonzero(big) in order to remove zeros from the vectors
Stian Olsen
on 30 Oct 2018
Stephen23
on 30 Oct 2018
@Stian Olsen: note that this a complex and inefficient way to do this task:
For much simpler and more efficient code see Torsten's answer.
madhan ravi
on 30 Oct 2018
exactly I agree with Stephen but maybe the OP is requested to stick to for loop since its a project?
Stephen23
on 30 Oct 2018
@madhan ravi: that is possible, but even so it is important to make it clear that this is a bad approach to writing MATLAB code.
madhan ravi
on 30 Oct 2018
yes I completely agree with you @Stephen
Categories
Find more on Loops and Conditional Statements 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!