convert a matrix with some zero to non zero matrix
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Chad Greene
2016-4-3
编辑:Chad Greene
2016-4-3
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 个评论
更多回答(3 个)
Star Strider
2016-4-3
编辑:Star Strider
2016-4-3
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 个评论
Image Analyst
2016-4-3
编辑:Image Analyst
2016-4-3
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
2016-4-3
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!