trouble with finding sum in a for loop

1 Ansicht (letzte 30 Tage)
Alexya
Alexya am 20 Okt. 2022
Bearbeitet: Matt J am 20 Okt. 2022
I have a for loop that is supposed to find the sum of the vector. It works with most vectors except those with zeros, please help. the specific input i have trouble with is
an2 = findSum([5 5 5 0 0])
function [sum] = findSum(vector)
sum = 0;
a = 1:20;
for i = vector
sum = sum + a(i);
end
end
  1 Kommentar
Dyuman Joshi
Dyuman Joshi am 20 Okt. 2022
(Assuming it is necessary for you to use the for loop)
You want to calculate the sum of a vector, but why are you not using that vector or its elements for the operation?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 20 Okt. 2022
Bearbeitet: Matt J am 20 Okt. 2022
You should of course never do it this way.
an2 = findSum([5 5 5 0 0])
an2 = 15
function result = findSum(vector
result=0;
for v_i = vector
result=result + v_i;
end
end

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by