Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Replace NaN in cell array with zero

72 views
Skip to first unread message

Cat

unread,
Sep 10, 2010, 9:40:10 AM9/10/10
to
Hello everybody,

I'm having a wee problem trying to figure out how to replace all NaN's in my cell array with a value of zero.

A simplified version of my array looks something like this:
x=
[1,2,0,4,NaN] [1,2,3,NaN,NaN] [1,5,7,4,NaN] [1,2,0,4,NaN] [1,2,0,4,NaN]
[NaN,2,0,4,NaN] [1,2,5,5,NaN] [7,2,0,4,NaN] [1,2,0,4,NaN] [1,5,0,4,NaN]
[1,2,NaN,4,NaN] [7,2,0,4,NaN] [1,5,0,4,NaN] [1,2,0,4,NaN] [5,2,0,4,NaN]
[1,7,5,5,NaN] [1,NaN,0,4,NaN] [1,2,0,4,NaN] [1,NaN,0,4,NaN] [1,2,7,4,NaN]
[1,2,0,4,NaN] [NaN,2,0,4,NaN] [NaN,2,NaN,4,NaN] [7,7,0,4,NaN] [1,5,0,4,NaN]

(okay it didn't format correctly but i guess you could get a rough idea)

From looking at answers to similar questions online i've attempted the following solutions:
x(isnan([x{:}]))={0}
and
x(cellfun(@isnan,x))={0}

but neither seem to do what i want.

I'd really appreciate any help,

Thanks, Cat

James Tursa

unread,
Sep 10, 2010, 11:02:22 AM9/10/10
to
"Cat " <c.o'con...@vet.gla.ac.uk> wrote in message <i6dcfq$n8n$1...@fred.mathworks.com>...

You might define your own function for this and use cellfun with it. e.g.,

function x = nanzero(x)
x(isnan(x)) = 0;
return
end

cellfun(@nanzero,x,'UniformOutput',false)


James Tursa

Matt Fig

unread,
Sep 10, 2010, 11:09:05 AM9/10/10
to
Another approach:

% Data
x = {[1,2,0,4,NaN] [1,2,3,NaN,NaN] [1,5,7,4,NaN]}

% Engine
B = cellfun(@isnan,x,'Un',0);
for ii = 1:length(x),x{ii}(B{ii}) = 0;end

Oleg Komarov

unread,
Sep 10, 2010, 11:20:23 AM9/10/10
to
Another solution may be:

In = cell2mat(In(:));
In(isnan(In)) = 0;
In = reshape(num2cell(In,2),5,5);

Oleg

Matt Fig

unread,
Sep 10, 2010, 11:40:21 AM9/10/10
to
"Matt Fig" <spam...@yahoo.com> wrote in message <i6dhmh$dkf$1...@fred.mathworks.com>...

Even simpler:

% Data
x = {[1,2,0,4,NaN] [1,2,3,NaN,NaN] [1,5,7,4,NaN]}

% Engine
for ii = 1:length(x),x{ii}(isnan(x{ii})) = 0;end

Thomas Vanaret

unread,
Sep 13, 2010, 4:27:25 AM9/13/10
to
I know I'm a bit late, but after (some) reflexion, I've found a one line solution without any loop using nansum (Statistical Toolbox - sorry)

% input
x = {[1,2,0,4,NaN] [1,2,3,NaN,NaN] [1,5,7,4,NaN]; [NaN,2,0,4,NaN] [1,2,5,5,NaN] [7,2,0,4,NaN]} % 2 x 3 cell array

% solution
y = cellfun(@(M) nansum(M,1), x, 'UniformOutput', false)


% Explanation : nansum(NaN) return 0

0 new messages