MATLAB Answers

Raza
0

Replacing NaNs with zero in a matrix within a cell array.

Asked by Raza
on 22 Jan 2019
Latest activity Edited by Andy Campbell on 1 Mar 2019
How to replace NaNs with 0 in a cell array that has the following anatomy 13x1 cell, Each cell is of size 63x63[double]. the cell name is 'a'.
Any help would be appreciated, Thank you in advance.

  2 Comments

what do you mean by the 'cell name'
the name of the cell array is 'a'. sorry for the confusion.

Sign in to comment.

3 Answers

Answer by Walter Roberson
on 22 Jan 2019
 Accepted Answer

a = cellfun(@(M) subsasgn(M, substruct('()', {isnan(M)}), 0), a, 'uniform', 0);
No loop needed... just ugly code.

  1 Comment

the code works just fine for me, thank you for your help.

Sign in to comment.


Answer by Andy Campbell on 1 Mar 2019
Edited by Andy Campbell on 1 Mar 2019

The fillmissing function is built for this, you just need to use cellfun since each of these doubles are included in the cell array.
nanless = cellfun(@(c) fillmissing(c,'constant',0), a,'UniformOutput',false)
If you don't want to use cellfun, since it looks like you data is all uniform you can also do this by putting each cell into an array, applyin fillmissing, and then reshaping it back into the cell array:
array = [a{:}]; % This works because they are all 63x63
array = fillmissing(array,'constant',0);
a = mat2cell(array, 63, ones(1,13)*63)
and of course this can all be one-lined
a = mat2cell(fillmissing([a{:}],'constant',0), 63, ones(1,13)*63);

  0 Comments

Sign in to comment.


Answer by Omer Yasin Birey on 22 Jan 2019
Edited by Omer Yasin Birey on 22 Jan 2019

% a = cell(13,1);
% %initializing the values
% for i = 1:length(a)
% a{i} = nan(63,63);
% end
%removing the nans
for k = 1:size(a,1)
for j = 1:size(a,2)
a{k,j}(isnan(a{k,j}))=0;
end
end

  1 Comment

thank you so much for your help.

Sign in to comment.