필터 지우기
필터 지우기

Substracting matrix with NaN values

조회 수: 1 (최근 30일)
FC93
FC93 2017년 3월 8일
댓글: FC93 2017년 3월 8일
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]

채택된 답변

Walter Roberson
Walter Roberson 2017년 3월 8일
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.
  댓글 수: 1
FC93
FC93 2017년 3월 8일
Thank you for your help. This is exactly what I need.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KSSV
KSSV 2017년 3월 8일
편집: KSSV 2017년 3월 8일
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] ;
% E=[ -2 -2 -6; -8 -5 -12; -14 NaN NaN] ;
R(:,:,1) = A ;
R(:,:,2) = -B ;
R(:,:,3) = -C ;
R(:,:,4) = -D ;
iwant = nansum(R,3)
You have to cross check your E once.
Other method using loops:
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] ;
E=[ -2 -2 -6; -8 -5 -12; -14 NaN NaN] ;
R(:,:,1) = A ;
R(:,:,2) = -B ;
R(:,:,3) = -C ;
R(:,:,4) = -D ;
% iwant = nansum(R,3)
[m,n,p] = size(R) ;
iwant = NaN(m,n) ;
for i = 1:m
for j = 1:n
k = squeeze(R(i,j,:)) ;
k = k(~isnan(k)) ;
if ~isempty(k)
iwant(i,j) = sum(k) ;
end
end
end
  댓글 수: 1
FC93
FC93 2017년 3월 8일
Thank you for your help.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by