# simple for cycle!

10 views (last 30 days)
Paul Rogers on 15 Jan 2020
Commented: Paul Rogers on 15 Jan 2020
I have one vector:
massa=massa =
-0.2000
-0.1932
-0.1729
-0.1397
-0.0946
-0.0386
0.0265
0.0992
0.1773
0.2587
0.3413
0.4227
0.5008
0.5735
0.6386
0.6946
0.7397
0.7729
0.7932
0.8000
I run this cycle to have to have two separate vectors (one for negative valuse and one for positive values), one for the negative massa, and one for the positive:
for i=1:length(massa)
if massa(i) < 0
massa_neg(i) = massa(i);
else
massa_pos(i) = massa(i);
end
end
I get the right for the massa_neg but for massa_pos it puts zeros instead of nothing:
0 0 0 0 0 0 0,0265259209387866 0,0991522876735153 0,177257256429600 0,258710327263834 0,341289672736166 0,422742743570400 0,500847712326485 0,573474079061213 0,638640785812871 0,694570254698197 0,739736875603245 0,772908620850317 0,793180651701361 0,800000000000000

Jakob B. Nielsen on 15 Jan 2020
Edited: Jakob B. Nielsen on 15 Jan 2020
Think what happens for massa_pos when i=1. Nothing happens, because massa(i) is negative. But when you get to i=7, you then get massa_pos(7)=massa(7). What is matlab to think massa_pos(1:6) consists of, when you have not told anything about it? A vector will be filled with 0s as default.
negcounter=1;poscounter=1;
for i=1:length(massa)
if massa(i) < 0
massa_neg(negcounter) = massa(i);
negcounter=negcounter+1;
else
massa_pos(poscounter) = massa(i);
poscounter=poscounter+1;
end
end
Alternatively, a more clean approach is to simply use logical indexing:
massa_neg=massa((massa < 0)); %all values of massa which is below 0
massa_pos=massa((massa >= 0)); %and, similarly, all values of massa which is greater than or equal to 0.

#### 1 Comment

Paul Rogers on 15 Jan 2020
thanks for the explanation.
I'll use:
massa_neg=massa((massa < 0)); %all values of massa which is below 0
massa_pos=massa((massa >= 0)); %and, similarly, all values of massa which is greater than or equal to 0.
It's perfect and easy!

R2014b

### Community Treasure Hunt

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

Start Hunting!