From: Wendy on
Hi all,

I have a matrix

a =[
3 0 3 2
1 3 0 1
9 3 4 0
0 8 1 0];
I want to change all the zeros to NaN. I used [r,c,v]=find(a==0); to find row indices and column indices of all the zero elements. I know I can loop all the elements in the r and c vectors to do that. Is there any way that I can change all the 0 elements to NaN at once. I tried a(r,c) = NaN, but it does not work.

Thank you,
Wendy
From: Steven Lord on

"Wendy " <wlq121(a)gmail.com> wrote in message
news:hpfcni$b5$1(a)fred.mathworks.com...
> Hi all,
>
> I have a matrix
>
> a =[
> 3 0 3 2
> 1 3 0 1
> 9 3 4 0
> 0 8 1 0];
> I want to change all the zeros to NaN. I used [r,c,v]=find(a==0); to find
> row indices and column indices of all the zero elements. I know I can loop
> all the elements in the r and c vectors to do that. Is there any way that
> I can change all the 0 elements to NaN at once. I tried a(r,c) = NaN, but
> it does not work.

Use logical indexing rather than FIND.

a(a==0) = NaN;

If later on you want to replace the NaN values with something else, using
the following will NOT work, because NaN is not equal to anything, not even
another NaN:

a(a==NaN) = -99;

Instead you'd need to use:

a(isnan(a)) = -99;

--
Steve Lord
slord(a)mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ


From: us on
"Steven Lord"
> Instead you'd need to use:
>
> a(isnan(a)) = -99;
>
> --
> Steve Lord

or

a(a~=a)=-99;
% which used to be a bit faster in older ML versions...

us