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

1 次查看(过去 30 天)
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!

采纳的回答

DGM
DGM 2021-3-24
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 个评论
DGM
DGM 2021-3-24
Your result is correct. Check the value of Sumtoend. It is [41 27 6]. If you're looking at what's printed to console, that's B, not the result.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by