简体   繁体   中英

Matlab: subtract vectors in a 3D array by a list of vectors

I have n groups, each group has m vectors of dimension d. These are represented by ad*m*n matrix A.

I have n vectors of dimension d, represented by ad*n matrix B.

Now I would like to subtract all the m vectors in the group i by the corresponding vector i in B (and I do that for all i = 1,...,n).

This can be done simply like:

C = zeros(size(A));
for  i = 1:n
    for j = 1:m
        C(:,j,i) = A(:,j,i) - B(:,i);
    end
end

However, this is quite slow because of the loop. Could anybody please suggest me a very fast way to do that?

Thank you in advance for your help.

bsxfun完美案例 -

C = bsxfun(@minus,A,permute(B,[1 3 2]))

Give this a shot:

B = repmat(reshape(B,[d 1 n]),[1 m 1]);
C = A - B;

EDIT

Divakar's solution is faster. For 100 runs with d=50;m=75;n=100; the average times were as follows:

Nesbit's - .0165s
Divakar's - .0013s
Mine - .0023s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM