매트릭스 추가 NAN 값을 건너 뛰는 것
문제
건너 뛰는 동안 매트릭스에 대한 요소 현명한 추가를하고 싶습니다. 난 가치. Matlab과 Octave가 있습니다 Nansum, 그러나 매트릭스 내에서 현명한 추가 기능을 수행합니다.
허락하다:
a = NaN * zeros(3)
b = ones(3)
원해요:
c = nan+(a, b)
그리고
c = b
그리고:
d = nan+(a,a)
그리고
d = a
해결책
N+1 차원을 따라 ND 어레이를 촉진하는 경우에도 여전히 Nansum을 사용할 수 있습니다.
2d
% commands de-nested for readability. You can do this with a single line, of course
tmp = cat(3,a,b);
c = nansum(tmp,3);
일반적인 경우
function out = nansumByElement(A,B)
%NANSUMBYELEMENT performs an element-wise nansum on the n-D arrays A and B
% A and B have to have the same size
% test input
if nargin < 2 || isempty(A) || isempty(B) || ndims(A)~=ndims(B) || ~all(size(A)==size(B))
error('please pass two non-empty arrays of the same size to nansumByElement')
end
% calculate output
nd = ndims(A); % get number of dimensions
% catenate and sum along n+1st dimension
out = nansum(cat(nd+1,A,B),nd+1);
다른 팁
a_fixed = a;
a_fixed(isnan(a)) = 0;
b_fixed = b;
b_fixed(isnan(b)) = 0;
c = a_fixed.+b_fixed;
제휴하지 않습니다 StackOverflow