Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generalized Matrix Product

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
like image 624
Nick Avatar asked Nov 08 '11 22:11

Nick


People also ask

What is general matrix multiply?

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 do you find the product of a matrix?

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.

Can you multiply a 2x3 and 2x2 matrix?

For example, the 2 × 2 and 2 × 3 matrices of multiplication are possible and the resultant matrix is a 2 × 3 matrix.

How do you define a matrix product?

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.


2 Answers

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.

like image 72
Divakar Avatar answered Oct 14 '22 10:10

Divakar


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
like image 34
Cavaz Avatar answered Oct 14 '22 10:10

Cavaz