필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Hokkien
Hokkien 2021년 3월 24일
댓글: Hokkien 2021년 3월 24일
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.
Hokkien
Hokkien 2021년 3월 24일
Oh yes, it is correct. Thanks for your help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by