Search code examples
matlabnancell-array

Index of scalar NaNs in cell array


Consider the following cell array:

test = cell(2,2);
test(1,:) = {NaN};
test{2,1} = [1,2,3];
test{2,2} = [4,NaN,6];

I would like to identify those cells which directly consist of an NaN scalar. I tried isnan in conjunction with cellfun, however, that identifies all NaNs within a vector as well.

nanIdx = cellfun(@isnan, test, 'UniformOutput', false)

As a result I am looking for nanIdx = [true,true ; false,false] of type logical.


Solution

  • You can define the anonymous function as @(x)isscalar(x) && isnan(x):

    nanIdx = cellfun(@(x)isscalar(x) && isnan(x), test)
    

    More conditions can be provided using any of is* functions.