delete NaN values from Matrix & use Matrix for other operations

1 view (last 30 days)
hey guys, I hope y'all can help me out with some awesome codes. Here is what I'm trying to do:
I have two 17759x1 double matrices, which I want to plot in order to analyze correlation. But both have some NaN values which I want to delete (shorten the matrices). In addition, one matrix sometimes has the value 9999, which I want to delete as well. I get stuck here already. The next part might be even more tricky, because the values have a time-dependency, meaning that if I delete one value(row) in one matrix I have to delete the same row(index) in the other Matrix as well, in order to plot them correctly in the end. Thanks in advance !

Accepted Answer

Jorg Woehl
Jorg Woehl on 12 Mar 2021
% Sample arrays
A = [1; 2; 3; 4; NaN; 6; NaN; 8; 9; 10];
B = [NaN; 12; 13; NaN; 15; 16; 17; 18; 9999; 20];
We want to get rid of elements 5 and 7 (from vector A) and 1, 4, and 9 (from vector B). This can be done by first creating a logical array of the same size as A and B that contains 1 (logical true) for the elements that need to be discarded:
idx = (isnan(B) | isnan(A) | (A==9999) | (B==9999))
idx =
10×1 logical array
1
0
0
1
1
0
1
0
1
0
Once this is done, we can use idx to delete these marked elements from A and B:
A(idx) = []
B(idx) = []
A =
2
3
6
8
10
B =
12
13
16
18
20

More Answers (1)

Walter Roberson
Walter Roberson on 12 Mar 2021
Edited: Walter Roberson on 12 Mar 2021
discards = 9999; %could be vector of values
mask = isnan(First) | isnan(Last) | ismember(First, discards) | ismember(Second, discards);
selectedFirst = First(~mask);
selectedSecond = Second(~mask);
selectedTimes = Times(~mask);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!