Finding specific elements in matrix without using loops or conditional statements

조회 수: 7 (최근 30일)
Trying to find the sum of certain elements in a matrix. In this particular case, I'm trying to find all elements of the first row, all elements of the 2nd row from the 2nd element on, all elements of the 3rd row from the 3rd element on, and so on, so that it kinda of staircases its way down the element. I'm assuming there's a way to do this using the find function, but it isn't popping out at me. Thank you for any help!
  댓글 수: 2
Jan
Jan 2016년 11월 3일
It sounds like a homework question. If so, please mention it explicitely, because if we post a working solution, you cannot deliver a solution without cheating anymore.
wakakami
wakakami 2016년 11월 3일
Appreciate it. I should have made it more explicit that I was just looking for a specific function which mimics the aforementioned pattern, in which case just knowing of triu existence is more than enough

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

채택된 답변

KSSV
KSSV 2016년 11월 3일
The stair case step you said will give you upper triangular matrix. You can make upper triangular matrix of given matrix and find it's sum. doc triu.
M = rand(5) ;
iwant = triu(M) ;
sum_iwant = sum(iwant(:)) ;

추가 답변 (1개)

Jan
Jan 2016년 11월 3일
Because this sound like a homework, here is a hint only:
mask = triu(true(size(X)));
X(~mask) = 0;
Of course a simple loop solves your problem also:
X = rand(4, 4);
Result = zeros(1, 4);
for iRow = 1:4
Result(iRow) = sum(...)
end

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by