Parseval
Parseval

Reputation: 833

Creating a new array that ignores NaN entries

I have the following array with some sequence of NaN entries:

A = [..., 14, 19, 32, 41, NaN, NaN, NaN, 4, NaN, 51, 62, 74, 58, ...]

In a loop, I want to go through the array and when I find the first NaN, I want to construct another array B where I use the 4 preceding values and the first 4 non-NaN values that comes after the first NaN I find. So my B should look like this:

B = [14, 19, 32, 41, 4, 51, 62, 74, 58]

Obviously I can't use B = A(~isnan(A)) because this will just create an A but without the NaN's which I don't want.

Is there a neat way to do this?

Upvotes: 0

Views: 87

Answers (1)

Wolfie
Wolfie

Reputation: 30046

You can use find to get the first NaN, and use this to get the last or first 4 elements from the non-NaN elements before and after respectively:

A = [1, 2, 3, 14, 19, 32, 41, NaN, NaN, NaN, 4, NaN, 51, 62, 74, 58, 4, 5, 6];

idxNaN = find( isnan(A), 1 );
idxOK = ~isnan(A);

B = A( [ find(idxOK(1:idxNaN-1), 4, 'last'), idxNaN+find(idxOK(idxNaN+1:end), 4) ] );

B =
    14    19    32    41     4    51    62    74

One nice thing here is that find will only return up to 4 elements (or however many you request), so you won't get an error if there are fewer available before/after the NaN. This code does assume there's at least one NaN - you could check whether idxNaN is empty to make this more robust.

Upvotes: 3

Related Questions