# how to find a number in cell and make it NaN?

3 views (last 30 days)
MP on 9 Aug 2022
Answered: MP on 10 Aug 2022
I have a cell matrix with size 1165x1 cell. In each cell there is one value i.e. number 31 that needs to be found and made NaN.
For example:
A = {[1,2],[3,4],[5 31], [31,6]};
I would like to make 31 = NaN where ever it is seen. Just like matrix B:
B = {[1,2],[3,4],[5 NaN], [NaN,6]};
Any help is greatly appriciated.

Jan on 9 Aug 2022
Edited: Jan on 9 Aug 2022
A = {[1,2], [3,4], [5 31], [31,6]};
B = A;
for k = 1:numel(B)
b = B{k};
m = (b == 31);
if any(m)
b(m) = NaN;
B{k} = b;
end
end
This can be condensed into a cellfun method:
p = [1, NaN];
B = cellfun(@(a) a .* p((a == 31) + 1), A, 'UniformOutput', 0)
B = 1×4 cell array
{[1 2]} {[3 4]} {[5 NaN]} {[NaN 6]}

Manas Shivakumar on 9 Aug 2022
There are several ways to do this.
1) convert to matrix, replace and convert back to cell array:
tmp = cell2mat(A);
tmp(tmp == 31) == Nan;
A = num2cell(tmp)
2) use cellfun:
A(cellfun(@(elem) elem == 31, A)) = {Nan}
dpb on 9 Aug 2022
The num2cell conversion also destroys the original cell sizes by placing every element into its own cell. One would have to write something like
mat2cell(cell2mat(A),,[2 2 2 2])
ans =
1×4 cell array
{1×2 double} {1×2 double} {1×2 double} {1×2 double}
>>
to get the original back.

MP on 10 Aug 2022
Thank you so much to everyone for their valuable time and efforts.
It saved a lot time of mine!