MATLAB Answers

# How can I multiply the columns of one matrix by another matrix most efficiently?

1 view (last 30 days)
Brandon on 12 Jul 2016
Commented: Brandon on 12 Jul 2016
I need to multiply the columns of one matrix by the columns of another matrix element-wise, and I would like to avoid loops. So far, I know that this will accomplish what I want done, but I would like to vectorize it if possible.
A = [1 2 3; 4 5 6; 7 8 9];
B = [1 1 1; 2 2 2; 3 3 3];
j = 1:size(A,2);
for i = 1:size(A, 2) % loop over columns
result(:, i*j) = bsxfun(@times, A(:, i), B);
end
Basically, given 2 MxN matrices my code outputs an MxN^2 matrix. Is there any built in function that will allow me to do this without the loop?
Thanks.
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Andrei Bobrov on 12 Jul 2016
Edited: Andrei Bobrov on 12 Jul 2016
reshape(bsxfun(@times,B,permute(A,[1,3,2])),size(A,1),[])
##### 1 CommentShowHide None
Brandon on 12 Jul 2016
Thanks, this does exactly what I needed.

Sign in to comment.

### More Answers (1)

Azzi Abdelmalek on 12 Jul 2016
A.*B
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!