====== Matrix Multiplication ======
===== Introduction =====
==== Prerequisites ==== It is assumed that those reading this have a basic understanding of what a matrix is and [[Matrix Addition|how to add them]], and multiply them by scalars, i.e. plain old numbers like 3, or -5. A secondary school algebra course would probably give one more than enough background, but is surely not required by any means.
If you need some background [[http://en.wikipedia.org/wiki/Matrix_%28mathematics%29|Go here]]
==== Matrix Multiplication Basics ==== In order to multiply 2 matrices given one must have the same amount of rows that the other has columns. In other words two matrices can be multiplied only if one is of dimension m×n and the other is of dimension n×p where m, n, and p are natural numbers {m,n,p }. The resulting matrix will be of dimension n×n.
=== Example 4x2 Multiplied by 2x4 === Take a matrix 4x2 call it ; another of dimension 2x4 and call it . Give them some arbitrary values and lets do some multiplication.
Our result matrix is going to be 2×2 as you will see as we go step by step. First we multiply and sum the first row with the first column: 2(3) + 3(2) + (-1)(-1) + 0(2). Then we do the same for the first row and second column: 2(4) + 3(1) + (-1)(2)+ 0(7), etc.
To make a long story short, our matrix would be:
As this implies, multiplication is non-commutative in general for matrices, i.e. since in this case if we reversed the order the resulting matrix would be 4×4 instead of 2×2.
=== More General Approach ===
Now lets visualize A and B as m×n and n×p matrices respectively.
We are going to be adding and multiplying like before, but generally.
==== Psedocode & General Algorithm ====
So now that we have a general idea of what a matrix is, and how to multiply them in general, we can derive some psedocode around it. We could break down the steps as follows.
Here is some psedocode treating matrices like if they have a m element and an n element, so the dimension of a matrix object is m×n.
multiplyMatrix(matrix1, matrix2)
-- Multiplies rows and columns and sums them multiplyRowAndColumn(row, column) returns number var total: number begin for each rval in row and cval in column begin total += rval*cval end return total end
begin
-- If the rows don't match up then the function fails
if matrix1:n != matrix2:m return failure;
dim = matrix1:n -- Could also be matrix2:m newmat = new squarematrix(dim) -- Create a new dim x dim matrix for each r in matrix1:rows and c in matrix2:columns begin
end
end
<\/code>
===== Implementations =====
==== C# ====
==== VB ====
==== Python ====
==== Ruby ====
==== Javascript ====
==== Java ====
==== Squeak / Smalltalk ====
==== Scheme / Lisp ====
==== C ====
[[http://angelo.freeshell.org/computer/docs/mmult.php|Single Dimension arrays in C]]
[[Category:Algorithms]]