问题
I have two matrices A
and B
, both of size 4x4
. multiply the first column of A
with all the other columns of B
with:
bsxfun(@times, A(:,1),B)
but what I want to do is to repeat this operation for each column of A
, i.e multiply all columns of A
by all columns of B
. How can I do this with bsxfun
(without loops or repmat
)?
回答1:
Yes, by permuting the dimensions of one of the matrices to make it a 4x1x4 array:
permute(bsxfun(@times, A, permute(B, [1 3 2])), [1 3 2])
回答2:
Alternatively:
>> n = size(A, 1);
>> res = arrayfun(@(x) A(:, x) * ones(1, n) .* B, 1 : n, 'UniformOutput', false)
res =
[4x4 double] [4x4 double] [4x4 double] [4x4 double]
A remark: in Matlab "multiply" by default means matrix multiplication, which would be simply res = A' * B
. What you asked is Element wise multiplication.
来源:https://stackoverflow.com/questions/18959675/multiply-all-columns-of-one-matrix-by-another-matrix-with-bsxfun