필터 지우기
필터 지우기

how to do sum of element of multiple number in matlab?

조회 수: 3 (최근 30일)
Putri Basenda Tarigan
Putri Basenda Tarigan 2020년 11월 18일
댓글: Putri Basenda Tarigan 2020년 11월 18일
Hello everyone.
If I have
m=[3 3 4 3 2 4 3]
c=[3 4]
then I want to calculate the sum of m(c) at the same time
I tried
b=1:m(c)
b=sum(b)
but only give me one number. I want it to be 2 numbers. How to do this?
Thanks in advance
  댓글 수: 2
Timo Dietz
Timo Dietz 2020년 11월 18일
Could you please explain in more detail? Does c contain the indices up to which you like to sum up m - starting always from 1? Or why do you expect two numbers as result?
Putri Basenda Tarigan
Putri Basenda Tarigan 2020년 11월 18일
this means that for c=3, I want to sum m from 1 to 3, so it's 10. and for c=4, it's sum of m from 1 to 4, so it's 13.
then I want to achieve these two numbers to compare them in the next step

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

채택된 답변

Rik
Rik 2020년 11월 18일
b=cumsum(m);
b=b(c);
  댓글 수: 5
Timo Dietz
Timo Dietz 2020년 11월 18일
That's intersting. Many thanks for the insights.
Putri Basenda Tarigan
Putri Basenda Tarigan 2020년 11월 18일
Thank you Sir

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

추가 답변 (1개)

Timo Dietz
Timo Dietz 2020년 11월 18일
편집: Timo Dietz 2020년 11월 18일
Not sure whether I got your issue. But in case you want to summarize all members of m starting at index 1, up to each member of c (containing indices of m) individually, you can do this:
b=arrayfun(@(x) sum(m(1:x)), c)
  댓글 수: 2
Rik
Rik 2020년 11월 18일
Functions like arrayfun and cellfun tend to be slower than using a for loop. The exception appears to be the legacy calls of cellfun (so those with the char input, instead of a function handle).
Timo Dietz
Timo Dietz 2020년 11월 18일
I see. Thanks a lot for the details.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by