Multiply all columns of one matrix by another matrix with bsxfun

≡放荡痞女 提交于 2019-12-14 02:15:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!