convert a matrix with some zero to non zero matrix
2 views (last 30 days)
Show older comments
for example I have this matrix: [ 1 2 3 ; 1 0 0 ; 0 0 0; 4 5 6] I want this matrix: [ 1 2 3 ; 1 nan nan ; 4 5 6 ] (also delete zero rows completely.)
0 Comments
Accepted Answer
Chad Greene
on 3 Apr 2016
Edited: Chad Greene
on 3 Apr 2016
A = [ 1 2 3 ; 1 0 0 ; 0 0 0; 4 5 6];
% Find rows of all zeros:
zerorows = sum(A,2)==0;
% Discard rows of all zeros:
A(zerorows,:) = [];
% Find all remaining zeros in A:
leftoverzeros = A==0;
% Replace remaining zeros in A with NaNs:
A(leftoverzeros) = nan
0 Comments
More Answers (3)
Star Strider
on 3 Apr 2016
Edited: Star Strider
on 3 Apr 2016
One approach:
M = [ 1 2 3 ; 1 0 0 ; 0 0 0; 4 5 6]; % Original Matrix
M(M == 0) = NaN; % Set: ‘0’ —> ‘NaN’
Mn = ~isnan(M); % Values That Are Not ‘NaN’ Set To Logical ‘false’
M(sum(Mn,2) == 0,:) = [] % If All Columns Of Any Row Are ‘NaN’, Set That Row To ‘Empty’
M =
1 2 3
1 NaN NaN
4 5 6
EDIT — Added comment documentation for each line to describe what each line does. The code was not changed.
0 Comments
Image Analyst
on 3 Apr 2016
Edited: Image Analyst
on 3 Apr 2016
I don't care for one of the two other answers since it uses sum() and thus will not be general in the case where you have negative numbers in your array. For example Chad's will remove the third row the A = [ 1 2 3 ; 1 0 0 ; 2, -1, -1; 4 5 6] even though the third row is not all zeros. It will however work for the example you gave of all positive integers. However Star's will work in all cases because the sum is after the isnan() and it's summing a map of where nan's are rather than summing the original matrix.
I offer the more general, robust way of using either any() or all() (your choice as to which to use as they are equivalent):
A = [ 1 2 3 ; 1 0 0 ; 0, 0, 0; 4 5 6];
% Find rows where all are 0
zeroRows = ~any(A, 2)
% or alternatively you could do it this way
zeroRows = all(A == 0, 2)
% Delete rows of all zeros:
A(zeroRows,:) = [];
% Make any remaining zeros NaNs
A(A==0) = nan
Azzi Abdelmalek
on 3 Apr 2016
M = [ 1 2 3 ; 1 0 0 ; 0 0 0; -1 -1 2];
out=arrayfun(@(x) strrep(x,0,nan),M(any(~~M,2),:))
0 Comments
See Also
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!