Ava
Ava

Reputation: 67

How to replace NaNs of a vector to empty cells in matlab

I would like to replace NaNs of a vector with empty cells in matlab. Any suggestion would be much appreciated.

Upvotes: 3

Views: 1037

Answers (1)

Suever
Suever

Reputation: 65430

In an array you cannot replace a value with an empty value ([]). If you try to, this will simply remove that element therefore changing the size. This is because you are replacing a value of length = 1 with a value ([]) of length = 0.

a = [1, NaN, 2];

%// Replace all NaNs with []
a(isnan(a)) = [];

%// 1  2

This is likely why there are NaNs there in the first place. NaNs are a good placeholder within a numeric array.

If you do actually want empty values instead of NaN values, you would need to convert it to a cell array.

a = [1 NaN 2];

%// Convert to cell
acell = num2cell(a);

%// Replace all NaNs with []
acell(isnan(a)) = {[]};

%//  [1]    []    [2]

I would highly discourage you from doing this as cell array are significantly slower than a numeric array and whatever processing you are doing can likely be easily adapted to handle (or ignore) the NaN entries.

Upvotes: 3

Related Questions