No need for a loop:
positive_numbers = v(v>0);
negative_numbers = v(v<0);
zero_numbers = v(v==0);
.
See "Logical indexing"
.
--- Example based on Comment 1 and 2 ---
In your code in the comment you overwrite the variables with identical results a number of times. I meant "No loop needed".
I misunderstood your question. I thought you wanted separate the positive values from the negative values. DOUBLE in the example below communicates the intent. Matlab doesn't need it.
Run this code as is (without a loop)
v = [ 1, 5, -3, 0 ];
positive_numbers = v(v>0);
negative_numbers = v(v<0);
zero_numbers = v(v==0);
numbers_of_positives = sum( double( v>0 ) );
numbers_of_negatives = sum( double( v<0 ) );
numbers_of_zeros = sum( double( v==0 ) );
This certainly doesn't serve as an exercise with loops, but it returns a result.
Best Answer