How to sum only the positive elements in a vector using an If-Statement?
Afficher commentaires plus anciens
How do you only sum the positive elements in a vector using an if statement?
3 commentaires
Geoff Hayes
le 7 Oct 2014
Jason - what have you tried so far?
Jason
le 7 Oct 2014
Geoff Hayes
le 7 Oct 2014
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)
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Correlation and Convolution dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!