7

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?

Matthias Pospiech
  • 2,714
  • 15
  • 46
  • 65

3 Answers3

11

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}.

Rody Oldenhuis
  • 36,880
  • 7
  • 47
  • 94
  • If `x` is a matrix, you need to alter the anonymous function to `@(x) any(any(isnan(x)))` (i.e. add `any` for the second time, to ensure you get a scalar from the function)). – Martin Pecka Dec 11 '14 at 02:44
  • 1
    @peci1: you're right. Actually, more generally, it would be best to do `any(isnan(x(:))`, which works for arrays of any dimension and calls `any` only once. – Rody Oldenhuis Dec 11 '14 at 05:10
3

I found the answer on http://www.mathworks.com/matlabcentral/answers/42273

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

However, I do not understant it...

Matthias Pospiech
  • 2,714
  • 15
  • 46
  • 65
2
  • a(ind) = [] will remove the entries from the array
  • a(ind)= {''} will replace the NaN with an empty string.

If you want to delete the entry use = [] instead of = {''}.
If you wanted to replace the NaNs with a different value just set it equal to that value using curly braces:

a(ind) = {value}
Gunther Struyf
  • 11,083
  • 2
  • 31
  • 56