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

64 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 22 Jan 2019
a = cellfun(@(M) subsasgn(M, substruct('()', {isnan(M)}), 0), a, 'uniform', 0);
No loop needed... just ugly code.
  1 Comment
Raza on 22 Jan 2019
the code works just fine for me, thank you for your help.

Sign in to comment.

More Answers (2)

Omer Yasin Birey
Omer Yasin Birey on 22 Jan 2019
Edited: 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)

Andy Campbell
Andy Campbell on 1 Mar 2019
Edited: 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);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by