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.)

采纳的回答

Chad Greene
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

更多回答(3 个)

Star Strider
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.

Image Analyst
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
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),:))

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by