Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find NaN values is cell array

Tags:

matlab

cells

lets assume I have the following array:

a = {1; 'abc'; NaN}

Now I want to find out in which indices this contains NaN, so that I can replace these with '' (empty string).

If I use cellfun with isnan I get a useless output

cellfun(@isnan, a, 'UniformOutput', false)

ans = 
[          0]
[1x3 logical]
[          1]

So how would I do this correct?

like image 428
Matthias Pospiech Avatar asked Aug 10 '12 09:08

Matthias Pospiech


1 Answers

Indeed, as you found yourself, this can be done by

a(cellfun(@(x) any(isnan(x)),a)) = {''}

Breakdown:

Fx = @(x) any(isnan(x))

will return a logical scalar, irrespective of whether x is a scalar or vector. Using this function inside cellfun will then erradicate the need for 'UniformOutput', false:

>> inds = cellfun(Fx,a)
inds =
     0
     0
     1

These can be used as indices to the original array:

>> a(inds)
ans = 
    [NaN]

which in turn allows assignment to these indices:

>> a(inds) = {''}
a = 
    [1]
    'abc'
    ''

Note that the assignment must be done to a cell array itself. If you don't understand this, read up on the differences between a(inds) and a{inds}.

like image 78
Rody Oldenhuis Avatar answered Oct 07 '22 01:10

Rody Oldenhuis