simple for cycle!
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!