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!