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

Risposte (2)

madhan ravi
madhan ravi il 29 Ott 2018
Modificato: madhan ravi il 30 Ott 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 Commenti

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

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Prodotti

Release

R2018a

Richiesto:

il 29 Ott 2018

Modificato:

il 30 Ott 2018

Community Treasure Hunt

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

Start Hunting!

Translated by