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

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 commentaires

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?
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

Connectez-vous pour commenter.

 Réponse acceptée

Rik
Rik le 18 Nov 2020
b=cumsum(m);
b=b(c);

5 commentaires

KALYAN ACHARJYA
KALYAN ACHARJYA le 18 Nov 2020
Modifié(e) : KALYAN ACHARJYA le 18 Nov 2020
Yes sir, simplest
Uh, I wasn't aware of the cumsum function - nice. But for very large arrays it may be faster just to calculate the numbers needed -with arrayfun- instead of doing the cumulative sum over all members.
Rik
Rik le 18 Nov 2020
There is a trade-off here: arrayfun also has an overhead, as does the creation of the new array that has to be summed. I suspect cumsum will be faster if there are many elements in c, especially if they are towards numel(m). If there are few elements in c and they occur early in m, that might make arrafun faster (or actually: a for-loop).
That's intersting. Many thanks for the insights.
Thank you Sir

Connectez-vous pour commenter.

Plus de réponses (1)

Timo Dietz
Timo Dietz le 18 Nov 2020
Modifié(e) : Timo Dietz le 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 commentaires

Rik
Rik le 18 Nov 2020
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).
I see. Thanks a lot for the details.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by