Multiplying rows of matrix without bsxfun or for loops
Show older comments
I have two matrices A and B generated as follows:
x = 2;
y = 4;
A = kron(eye(x), ones(1,y));
littleB = horzcat(zeros(y-1,1),eye(y-1));
B = repmat(littleB, [1,x]);
I now want to multiply (element-wise) each row of A with each row of B to get a matrix output like:
0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1
I want to avoid the use of for-loops. I tried to use bsxfun but get an error (Non-singleton dimensions of the two input arrays must match each other), which I understand is caused by the fact that A has two rows (if A was just one row this would work). What would be the best way to achieve what I am trying to do? Any help would be much appreciated.
Accepted Answer
More Answers (1)
This is almost what you want, I think,
Bp=permute(B,[3 2 1]);
C=bsxfun(@times,A,Bp);
apart from the shape of the final result C. Although I don't see why you wouldn't prefer a 3D output.
3 Comments
If you want the result presented in the 2D form you propose,
Ap=permute(A,[2,3,1]);
C=bsxfun(@times,Ap,B.');
C=reshape(C,size(A,2),[]).'
This requires more transposing/permuting operations, which are expensive for large matrices. You could avoid this by organizing your data column-wise instead of row-wise.
Krunal
on 18 Sep 2014
No, Roger's is less efficient computationally (it requires data copying via repmat of A and B data whereas bsxfun does not), but his does have a simpler syntax, which can sometimes be just as important! Time you save in computation can be lost on debugging complicated-looking code.
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!