How to sum only the positive elements in a vector using an If-Statement?
조회 수: 12 (최근 30일)
이전 댓글 표시
How do you only sum the positive elements in a vector using an if statement?
댓글 수: 3
Geoff Hayes
2014년 10월 7일
Jason - your code above looks good. The statement if (vector(k) >= 0) will ensure that you only add positive numbers to your result local variable.
Note that in your line
result = result + sum(vector(k));
you don't need the sum function, since vector(k) is a single element. The above can be replaced with just
result = result + vector(k);
Note also, that the default step size, for loops, is 1. So the
for k = 1:1:length(vector)
can be replaced with
for k = 1:length(vector)
채택된 답변
Mohammad Abouali
2014년 10월 7일
You can do that without if
let's say d is your array of positive and negative numbers. You want to sum only the positive ones then just do this:
sum(d(d>0))
댓글 수: 3
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!