Adding elements of matrix according to criteria

2 次查看(过去 30 天)
Hi there,
I have a quick question which should be trivial to solve but I cannot figure out how to solve it.
I have 2 matrices:
  • Matrix A with dimensions (2x40x2x1000)
  • Matrix B with dimensions (2x40x2)
I want to add matrix A elements along the 4th dimension if the element is above the one on matrix B.
So if elements (1,1,1,:) of matrix A are bigger than element (1,1,1) of matrix B, I want to add them up. If elements (2,1,1,:) of matrix A are bigger than element (2,1,1) of matrix B, I want to add them up. etc
What is the easiest way to do it?

回答(2 个)

Matt J
Matt J 2015-3-9
编辑:Matt J 2015-3-9
mask=bsxfun(@gt,A,B);
result=sum(A.*mask,4);

Jan
Jan 2015-3-8
The term "add them up" is not clear. A small example would be nice. I guess it could mean something like this:
S = zeros(size(B));
for k = 1:1000
Ak = A(:, :, :, k);
M = Ak > B;
S(M) = S(M) + Ak(M);
end
Or:
S = zeros(size(B));
for k = 1:1000
Ak = A(:, :, :, k);
S = S + Ak .* (Ak > B);
end

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by