Reputation: 205
I would like to remove nans from two vectors, the vectors have to be the same length, so if I remove a nan in one vector, the corresponding value in the other vector must be removed even if it is not a nan. For example:
x = [1 nan 3 4 5]
y = [6 7 8 nan 10]
I would like to remove the nan in x, as well as the 7 in y. Also, I would like to remove the nan in y and the 4 in x, this way the vectors stay the same length. This question is similar to one asked here MATLAB: How To Efficiently Remove NaN Elements from Matrix , but I'm new to MATLAB and I am unsure of how to do the same with vectors instead of matrices. Thanks for the help.
Upvotes: 0
Views: 9075
Reputation: 777
This will ensure your vectors x and y remain the same size as each other but also that you only have the (x,y) pairs that are meaningful.
ind = ~isnan(x) & ~isnan(y) ;
xn = x(ind);
yn = y(ind);
Upvotes: 4
Reputation: 1081
The most efficient solution for memory management and speed is to remove values from your existing arrays using logical indexing, rather than creating new arrays.
xn = isnan(x); yn = isnan(y); % find the locations of the NaNs
x(xn | yn) = []; % delete elements from x that are NaN in x OR y
y(xn | yn) = []; % delete elements from y that are NaN in x OR y
But you won't notice the performance difference unless you have very large arrays.
Upvotes: 1
Reputation: 1345
Try the following:
x = [1 nan 3 4 5]
y = [6 7 8 nan 10]
id1 = find(isnan(x));
id2 = find(isnan(y));
x([id1,id2]) = []
y([id1,id2]) = []
Output:
x =
1 3 5
y =
6 8 10
Explanation:
find(isnan(x));
Creates a vector with indices of NaNs in x
. The same we do for y
. Then, we concatenate two vectors using [id1,id2]
. Finally, x([id1,id2]) = []
removes elements from vectors where NaNs are present.
Upvotes: 1