Why does my vector turn into a single number in a FOR loop

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)

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

you should put i as an index number in order to prevent overwriting read more about loops and indexing
use nonzeros(small) and nonzero(big) in order to remove zeros from the vectors
It didn't work completely, the vectors just kept getting bigger when i ran the script several times, however it worked when i changet the code to this
x=randi(100,1,50);
small = [];
big = [];
for i = 1:numel(x)
if x(i)<=50
small(numel(small)+1)=x(i);
else
big(numel(big)+1)=x(i);
end
end
@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.
exactly I agree with Stephen but maybe the OP is requested to stick to for loop since its a project?
@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.
yes I completely agree with you @Stephen

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2018a

Asked:

on 29 Oct 2018

Edited:

on 30 Oct 2018

Community Treasure Hunt

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

Start Hunting!