Question

I have the following variables:

x = [0 1 2 2 3 4 5 6 7 8 9];
y = [0 1 2 nan 3 4 5 6 7 8 9];

I would like to pass 'y' through an equation to give 'y2', for example:

y2 = y.*2;

Note this is just an example. The real equation I have is more complicated. The 'real' equation does not allow nans to be within the vector (as one value depends on the last).

If I can't have nans passing through the equation, however, I can type

y2 = y(~isnan(y)).*2;

y2 =

     0     2     4     6     8    10    12    14    16    18

This removes the nan and then performs the calculation.

How can I make 'y2' to be back to the same length as 'x' i.e. with a nan as the fourth value?

Something like:

y2 =

     0     2     4   NaN     6     8    10    12    14    16    18

The reason I'm doing this is that I want to plot 'y2' against 'x' and thus they must be the same size.

I realize that I can do

x2 = x(~isnan(y))

and then just plot 'x2' against 'y2' but I would like to find a way of doing it the way I specify above.

Was it helpful?

Solution

Store the NaN indices somewhere and then use those to input the new values into the right places and then plug back in the NaN values too.

Code

%%// Define function
func1 = @(x)x*2;

%%// Input data - y
y = [0 1 2 nan 3 4 5 6 7 8 9];

%%// Store NaN indices
nan_ind = isnan(y)

%%// Process data on the function
y2(~nan_ind) = func1(y(~nan_ind))
y2(nan_ind) = NaN
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top