How to sum from a particular cell to last cell in a single row.
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
0 Kommentare
Akzeptierte Antwort
DGM
am 24 Mär. 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 Kommentare
DGM
am 24 Mär. 2021
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!