Question

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)?

Was it helpful?

Solution

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])

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top