simple for cycle!
조회 수: 7 (최근 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!