How to sum only the positive elements in a vector using an If-Statement?

34 ビュー (過去 30 日間)
Jason
Jason 2014 年 10 月 7 日
コメント済み: Amanda 2023 年 9 月 20 日
How do you only sum the positive elements in a vector using an if statement?
  3 件のコメント
Jason
Jason 2014 年 10 月 7 日
function result = sumPositive(vector)
%-------------------------------------------------
result = 0;
for k = 1:1:length(vector)
if (vector(k) >= 0)
result = result + sum(vector(k));
end
end
and the test program is
clear;
clc;
close all;
% Test 1 for sum of only postive integers
vector = [10, -5, 0, 12, 14];
result = sumPositive(vector);
disp('The sum of the positive elements is: ')
disp(result)
What I'm not sure of is I need to put a statement to skip the negative numbers or how would I deal with those?
Geoff Hayes
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
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 件のコメント
Camilo Malagon-Nieto
Camilo Malagon-Nieto 2017 年 6 月 2 日
編集済み: Camilo Malagon-Nieto 2017 年 6 月 2 日
beautifully simple!
Amanda
Amanda 2023 年 9 月 20 日
Hello, I think you are very beutiful. Are you married yet? (; (im over 18!)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by