How to sum from a particular cell to last cell in a single row.

1 view (last 30 days)
Hi all! I wish to sum from particular cell to last cell in a single row. Example:
I have a row A with values = [1 5 7 1 3 4 5 12 2 4]
And I want to sum cell 2 to last cell, cell 6 to last cell, and cell 9 to last cell.
I wish to have something like for loop with customize value so I can get the value of:
cell 2 to last cell = [5+7+1+3+4+5+12+4] = 41
cell 6 to last cell = [4+5+12+2+4] = 27
cell 9 to last cell = [2+4] = 6
I tried to use something like i=length(A):10, but it doesn't and I don't think it is correct as well.
Thanks for the help and I really appreciate it!

Accepted Answer

DGM
DGM on 24 Mar 2021
When indexing, you can use the 'end' keyword.
% this is the row vector
A=[1 5 7 1 3 4 5 12 2 4];
% pick a start index
% for demonstration, i'm picking a random one
start=randi(length(A),1);
% you can do this by indexing using the 'end' keyword
sumtoend=sum(A(start:end));
% or you could do it by knowing the vector length
% sumtoend=sum(A(start:length(A)));
% show the results
[start sumtoend]
  3 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by