Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
matrix manipulation

Subject: matrix manipulation

From: Wendy

Date: 6 Apr, 2010 13:25:06

Message: 1 of 3

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

Subject: matrix manipulation

From: Steven Lord

Date: 6 Apr, 2010 13:27:26

Message: 2 of 3


"Wendy " <wlq121@gmail.com> wrote in message
news:hpfcni$b5$1@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@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ

Subject: matrix manipulation

From: us

Date: 6 Apr, 2010 13:38:04

Message: 3 of 3

"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

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us