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

2 views (last 30 days)
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?
##### 2 CommentsShowHide 1 older comment
Putri Basenda Tarigan on 18 Nov 2020
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 on 18 Nov 2020
b=cumsum(m);
b=b(c);
Putri Basenda Tarigan on 18 Nov 2020
Thank you Sir

Timo Dietz on 18 Nov 2020
Edited: Rik on 18 Nov 2020
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 CommentsShowHide 1 older comment
Timo Dietz on 18 Nov 2020
I see. Thanks a lot for the details.