Why does my vector turn into a single number in a FOR loop
Mostra commenti meno recenti
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
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
madhan ravi
il 29 Ott 2018
you should put i as an index number in order to prevent overwriting read more about loops and indexing
madhan ravi
il 29 Ott 2018
use nonzeros(small) and nonzero(big) in order to remove zeros from the vectors
Stian Olsen
il 30 Ott 2018
Stephen23
il 30 Ott 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
il 30 Ott 2018
exactly I agree with Stephen but maybe the OP is requested to stick to for loop since its a project?
Stephen23
il 30 Ott 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
il 30 Ott 2018
yes I completely agree with you @Stephen
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!