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
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
% 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
In = cell2mat(In(:));
In(isnan(In)) = 0;
In = reshape(num2cell(In,2),5,5);
Oleg
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
% 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