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!