Effacer les filtres
Effacer les filtres

Adding elements of matrix according to criteria

2 vues (au cours des 30 derniers jours)
V
V le 8 Mar 2015
Modifié(e) : Matt J le 9 Mar 2015
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?

Réponses (2)

Matt J
Matt J le 9 Mar 2015
Modifié(e) : Matt J le 9 Mar 2015
mask=bsxfun(@gt,A,B);
result=sum(A.*mask,4);

Jan
Jan le 8 Mar 2015
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

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by