I'm fairly new to MATLAB. Normal matrix multiplication of a M x K matrix by an K x N matrix -- C = A * B
-- has c_ij = sum(a_ik * b_kj, k = 1:K)
. What if I want this to be instead c_ij = sum(op(a_ik, b_kj), k = 1:K)
for some simple binary operation op
? Is there any nice way to vectorize this in MATLAB (or maybe even a built-in function)?
EDIT: This is currently the best I can do.
% A is M x K, B is K x N
% op is min
C = zeros(M, N);
for i = 1:M:
C(i, :) = sum(bsxfun(@min, A(i, :)', B));
end
General Matrix Multiply (GEMM) is a common algorithm in linear algebra, machine learning, statistics, and many other domains. It provides a more interesting trade-off space than the previous tutorial, as there are many ways to break up the computation.
How to multiply two given matrices? To multiply one matrix with another, we need to check first, if the number of columns of the first matrix is equal to the number of rows of the second matrix. Now multiply each element of the column of the first matrix with each element of rows of the second matrix and add them all.
For example, the 2 × 2 and 2 × 3 matrices of multiplication are possible and the resultant matrix is a 2 × 3 matrix.
The product of two matrices will be defined if the number of columns in the first matrix is equal to the number of rows in the second matrix. If the product is defined, the resulting matrix will have the same number of rows as the first matrix and the same number of columns as the second matrix.
Listed in this post is a vectorized approach that persists with bsxfun
by using permute
to create singleton dimensions as needed by bsxfun
to let the singleton-expansion
do its work and thus essentially replacing the loop in the original post. Please be reminded that bsxfun
is a memory hungry implementation, so expect speedup with it only until it is stretched too far. Here's the final solution code -
op = @min; %// Edit this with your own function/ operation
C = sum(bsxfun(op, permute(A,[1 3 2]),permute(B,[3 2 1])),3)
NB - The above solution was inspired by Removing four nested loops in Matlab.
if the operator can operate element-by-element (like .*
):
if(size(A,2)~=size(B,1))
error(blah, blah, blah...);
end
C = zeros(size(A,1),size(B,2));
for i = 1:size(A,1)
for j = 1:size(B,2)
C(i,j) = sum(binaryOp(A(i,:)',B(:,j)));
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With