extracting non-zero elements in a matrix or an array

Hello, I have two questions. I would be so glad if you can please help me.
1. How can I extract the number of non-zero elements in a matrix or in an array?
2. I have 3x3 (3d) array which is a cell. How can I add the diagonal elements or off-diagonal elements in a cell?

 채택된 답변

Paulo Silva
Paulo Silva 2011년 4월 18일

8 개 추천

a=[1 0 2;3 4 5;0 7 8]
a(a~=0) %get all the non zero values
diag(a) %elements on the diagonal
s1=sum(diag(a)) %sum of the elements on the diagonal
sum(sum(a))-s1 %sum of non-diagonal elements

댓글 수: 3

thanks a lot. But what about for 3x3 cell? (I have a 3x3 cell each element is 500x2 matrix)
use the cellfun function or make a loop to apply the code to every cell element.
Thanks.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품

질문:

2011년 4월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by