MATLAB: How to get the nonzero elements

matrixzeros

hello,
I have a matrix that having a random coulmns and static number of rows ,and these columns contains alot of zeros,some of nonzero elements and i want to get the non zero elements in it and put it in a new matrix with the same static row.thanks in advance .
Ps i searched abt the nonzeros command but i cannot apply it on my code .

Best Answer

Ahmed, try this code to create the cell arrays based on a row-by-row process (which looks different than if you do it column by column):
m=[...
1 2 3 4 0 6
1 0 0 4 0 6
0 0 0 0 0 0
3 4 4 0 0 6
4 5 0 2 0 7]
[rows cols] = size(m)
caRow = 1;
for r = 1 : rows
thisRow = m(r, :);
nz = thisRow(thisRow ~= 0)
if ~isempty(nz)
ca{caRow} = nz;
caRow = caRow+1;
end
end
celldisp(ca)
Results:
ca{1} =
1 2 3 4 6
ca{2} =
1 4 6
ca{3} =
3 4 4 6
ca{4} =
4 5 2 7
Note how one whole row of all zeros is not included.