矩阵加法跳过 NaN 值

发布于 2024-08-15 08:41:02 字数 358 浏览 4 评论 0原文

我想对矩阵进行元素明智加法,同时跳过 NaN 值。 MATLAB 和 Octave 有 nansum,但它在矩阵内进行按列加法。

让:

a = NaN * zeros(3)
b = ones(3)


我想要:

c = nan+(a, b)

c = b


和:

d = nan+(a,a)

d = a

I would like to do element wise addition over matrices while skipping NaN values.
MATLAB and Octave have nansum, but it does column wise addition within a matrix.

Let:

a = NaN * zeros(3)
b = ones(3)

I want:

c = nan+(a, b)

and

c = b

and:

d = nan+(a,a)

and

d = a

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稚然 2024-08-22 08:41:02

如果您沿第 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);

You can still use nansum, if you catenate your n-d arrays along the n+1st dimension.

For 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);

The general case

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);
红尘作伴 2024-08-22 08:41:02
a_fixed = a;
a_fixed(isnan(a)) = 0;
b_fixed = b;
b_fixed(isnan(b)) = 0;
c = a_fixed.+b_fixed;
a_fixed = a;
a_fixed(isnan(a)) = 0;
b_fixed = b;
b_fixed(isnan(b)) = 0;
c = a_fixed.+b_fixed;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文