aulky11
aulky11

Reputation: 79

Replace NaN with zeros in cell array in MATLAB

I have a 50x25 cell array in the variable raw_data. Each cell contains a 200x150 matrix. I have a few NaN values scattered between all those values and I want to set them to zeros to make sure they do not interfere at later stages.

I have tried the following:

raw_data(cellfun(@(x) any(isnan(x), raw_data, 'UniformOutput', false)) = 0

When running the script, I get "Function 'subindex' is not defined for values of class 'cell'". Can anyone help me, please?

Thanks in advance!

Upvotes: 3

Views: 1652

Answers (1)

Dan
Dan

Reputation: 45752

How about this:

cellfun(@(x) nansum(x,ndims(x)+1), raw_data, 'UniformOutput', false)

Note if you're certain you'll only have 2D matrices in raw_data you can replace the ndims(x)+1 with 3.

The idea is to use nansum to sum along the 3rd dimension as this will preserve the shape of the first 2 dimensions and luckily nansum seems to convert NaN to 0 when all the elements being summed are NaN

Upvotes: 4

Related Questions