Replace corresponding elements in two different matrices

I have two matrices A and B. The matrix A contains missing data (shown as -9999) which I have replaced with NaN. Matrix B has no missing data. I want to replace the corresponding elements in B with NaN as well so the NaNs for both matrices are located in the same cells. How can I do that?

 Akzeptierte Antwort

Star Strider
Star Strider am 23 Nov. 2018
Try this:
A = [1 2 3 4; 5 NaN 7 8; 9 10 11 NaN]
B = randi(9, 3, 4)
NewB = B
NewB(isnan(A)) = NaN
producing:
A =
1 2 3 4
5 NaN 7 8
9 10 11 NaN
B =
2 7 6 8
5 8 3 4
7 7 4 1
NewB =
2 7 6 8
5 8 3 4
7 7 4 1
NewB =
2 7 6 8
5 NaN 3 4
7 7 4 NaN

4 Kommentare

Hi! Thank you for answering. I should have mentioned I am calculating correlation coefficients. I am using corr = corrcoef(A,B,'Rows','complete') which after reading the documentation again I realized that I think I solved my problem. Using that script should eliminate the rows in both matrices that contain NaN right?
The script that I wrote will not do that, because it wasn’t what you said you wanted.
This will:
A = [1 2 3 4; 5 NaN 7 8; 9 10 11 NaN; 6 10 12 13]
B = randi(9, 4)
Anan = any(isnan(A),2); % Find Rows With ‘NaN’ Values
Anew = A(~Anan, :)
Bnew = B(~Anan, :)
producing:
A =
1 2 3 4
5 NaN 7 8
9 10 11 NaN
6 10 12 13
B =
8 6 5 2
4 4 3 3
2 4 5 7
1 4 1 6
Anew =
1 2 3 4
6 10 12 13
Bnew =
8 6 5 2
1 4 1 6
That should do what you want.
What does the 2 do in the Anan row?
It’s the ‘dimension’ argument. In MATLAB, dimension=1 specifies column-wise operations (the default), down columns, and dimension=2 specifies row-wise operations, across rows. Here, I want the any function to identify rows with a NaN element in them, regardless of the column it appears in.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by