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

Dyuman Joshi
Dyuman Joshi 2022년 10월 20일
(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?

댓글을 달려면 로그인하십시오.

 채택된 답변

Matt J
Matt J 2022년 10월 20일
편집: Matt J 2022년 10월 20일

0 개 추천

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2022년 10월 20일

편집:

2022년 10월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by