MATLAB: Substracting matrix with NaN values

nansubstracting matrix

I have 4 matrix A, B, C and D. All matrix have NaN values, and matrix C and D have a lot of NaN values. Now I want to take A and substract B, C and D from it. I want that the result matrix contains only a NaN value if A has NaN or if A has a value but B, C and D do all have a NaN value. For example if a specific cell in A has a value, and the same cell has also a value in B but not in C and D (because there is an NaN) I want that matlab takes the NaN in C and B as 0. The matrix are really big so I con not do it by hand.
Example:
A=[ 1 2 3; 4 5 6; 7 NaN NaN] B =[ 1 2 3; 4 5 6; 7 2 NaN] C = [ 1 NaN 3; 4 5 6; 7 1 NaN] D = [ 1 2 3; 4 NaN 6; 7 1 NaN]
then A-B-C-D=E should be E=[ -2 -2 -6; -8 -5 -12; -14 NaN NaN]

Best Answer

mask = isnan(B) & isnan(C) & isnan(D);
tB = B; tB(isnan(B)) =0;
tC = C; tC(isnan(C)) =0;
tD = D; tD(isnan(D)) =0;
E = A - tB - tC - tD;
E(mask) = NaN;
Any nan in A will be carried through.