How do I sum the elements in a vector up to a specific value?

조회 수: 24 (최근 30일)
Anna Pierce
Anna Pierce 2021년 10월 25일
편집: the cyclist 2021년 10월 25일
I need to sum the numbers in an array up to the value 10. So with a function input of v=[2,3,2,2,1,3,1,10,3], I would not include 10 or any values after it in the sum. Below I have the function I am working with, I am currently getting an output of 18 instead of 14
function [prize]=sumPrize(v)
prize=0;
for i=1:length(v)<10
prize = prize + v(i);
end
end
  댓글 수: 1
the cyclist
the cyclist 2021년 10월 25일
편집: the cyclist 2021년 10월 25일
See my answer, but an explanation of why yours does not work is probably helpful.
Your loop does not do what you think it does. The line
for i=1:length(v)<10
is evaluated as follows:
  1. Calculate the length of the vector v, which is 9
  2. Create the vector 1:length(v), which is the vector [1 2 3 4 5 6 7 8 9]
  3. Test whether each element of that vector is less than 10. Since they all are, the result is [1 1 1 1 1 1 1 1 1]
  4. Loop over that vector
So, your for loop is equivalent to
for i = [1 1 1 1 1 1 1 1 1]
prize = prize + v(i);
end
which means you are just summing the 1st element of v, 9 times. That's why you get 18.

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

답변 (1개)

the cyclist
the cyclist 2021년 10월 25일
Here is one way:
v = [2,3,2,2,1,3,1,10,3];
prize = sum(v(1:find(v==10,1)-1))
prize = 14

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by