change only those zeros to NaN if all in row are 0

I have
a =
1 2 3
0 0 0
2 1 0
4 5 0
0 0 0
2 0 1
I need
b =
1 2 3
NaN NaN NaN
2 1 0
4 5 0
NaN NaN NaN
2 0 1
i.e. only if all elements in row are 0 replace with NaN

 採用された回答

Thomas
Thomas 2012 年 6 月 6 日

1 投票

a(any(a,2)==0,:)=NaN;
b=a

3 件のコメント

Image Analyst
Image Analyst 2012 年 6 月 6 日
Or reverse that, if a is not supposed to change:
b=a
b(any(b, 2) == 0, :) = NaN
per isakson
per isakson 2012 年 6 月 6 日
Shouldn't that be *all*:
b( all(b, 2) == 0, :) = NaN
Image Analyst
Image Analyst 2012 年 6 月 6 日
It works because any() looks for non-zeros, so it's only zero if there are no non-zeros, in other words, if they are all zeros. Perhaps my answer (not my comment above) might be more intuitive though - it used all().

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2012 年 6 月 6 日

0 投票

% Make a copy so we don't change a.
b=a
% Find out which rows are all zeros.
nonZeroRows = all(b == 0, 2)
% Assign all columns of the all-zero rows to nans.
b(nonZeroRows, :) = NaN

カテゴリ

製品

タグ

質問済み:

2012 年 6 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by