MATLAB: How to match matrics

match matrices

Suppose I have two matrices with same size (n x n),
A =
1 1 1
1 NaN 1
1 NaN 1
and
B =
NaN 2 NaN
2 2 2
2 2 2
How could I match these two matrices to get A =
NaN 1 NaN
1 NaN 1
1 NaN 1
and
B =
NaN 2 NaN
2 NaN 2
2 NaN 2
Many thanks.

Best Answer

Try this:
A(isnan(B)) = nan
B(isnan(A)) = nan