simple for cycle!

2 次查看(过去 30 天)
Paul Rogers
Paul Rogers 2020-1-15
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
Jakob B. Nielsen 2020-1-15
编辑:Jakob B. Nielsen 2020-1-15
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.
In your example, you can add a running counter;
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 个评论
Paul Rogers
Paul Rogers 2020-1-15
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!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2014b

Community Treasure Hunt

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

Start Hunting!

Translated by