質問

私はの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番目の次元に沿ってあなたのn次元配列をCATENATE場合は、

あなたはまだ、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;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top