Extract non zero elements from 2D array
Show older comments
Hi I have an array like this:

I want to extract non-zero elements for each row, e.g for second row, it should be 3,4. (and other array elements are zero) for third row 1,3,4 I think 3d array will be used and i tried this code, but incorrect results.
for m=1:r
for k=1:row
for l=1:col
if(a(k,l)~=0)
b(k,l,m)=a(k,l);
end
end
end
end
(a for array given above and b is new array with results) Any help will be highly appreciated.
Accepted Answer
More Answers (1)
Nicolaie Popescu-Bodorin
on 2 Apr 2017
Edited: Stephen23
on 2 Apr 2017
% Let A be a 2D Array and NZI the cell containing indices of non-zero elements on each column.
% preallocation:
sa = size(A,2); NZI{sa}=[];
for k=1:sa,
NZI{k} = find(A(:,k)~=0);
end
Kind regards, Nicolaie Popescu-Bodorin, www.lmrec.org/bodorin/
1 Comment
Tha saliem
on 2 Apr 2017
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!