Blah Blah
Blah Blah

Reputation: 59

Matlab Multiplication

If matrix A is in X, and matrix B is in Y.

Doing a multiplcation would just be Z = X*Y. Correct assuming same size for both arrays.

How can I compute it doing it with a for loop?

Upvotes: 2

Views: 290

Answers (3)

John Alexiou
John Alexiou

Reputation: 29264

Yes matrix multiplication is A*B and element by element is A*.B. If A is (NxM) and B is (MxK) size then the code for C=A*B is

update

for i=1:N
  for j=1:K
    C(i,j) = A(i,:)*B(:,j)
  end
end

Upvotes: 1

dvreed77
dvreed77

Reputation: 2387

Yes acai is correct, and I remember wondering the same thing when I started using Matlab. Just to provide some more detail to what acai said, LAPACK is Linear Algebra PACKage and is something a lot of other languages use to solve these types of problems, Python connects to it using SciPy, Java jlapack, etc.. BLAS is Basic Linear Algebra Subroutines, which handle the basic problem of matrix multiplication you are asking about. Acai is also right that you can never beat the performance Matlab gives for matrix multiplication, this is their bread and butter and they have spent decades now, optimizing the performance of these operations.

Upvotes: 3

Yanshuai Cao
Yanshuai Cao

Reputation: 1297

The anwser by ja72 is wrong, see my comments under it to see why. In general, in these simple linear algebra operations, it's impossible for your code to beat the vectorized version, not even if you write your code in C/mex (unless you have a certain sparsity structure in your matrix that you can exploit in your code). The reason is that under the hood, Matlab passes the actual job of matrix multiplication to Lapack library, written in Fortran, which then calls Blas libraries that are optimized given particular machine architecture.

Upvotes: 3

Related Questions