MATLAB: Extracting non-zero elements in a matrix or an array

indexingMATLABmatrixurgent

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 3×3 (3d) array which is a cell. How can I add the diagonal elements or off-diagonal elements in a cell?

Best Answer

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