Docsity

Matrix Multiplication: Inner Product and Outer Product - Prof. Marc Smith, Study notes of Computer Science

Toggle sidebar
bg1
Page 1
MATRIX MULTIPLICATION
C = A*B Def: ∑
=
=n
kkjikij BAC
1
The matrix sizes are: A is m x n, B is n x p, C is m x p.
Sum the elements multiplied by the elements
of this row of this column.
∗
=
npnjn
pj
pj
mnmm
inii
n
BBB
BBB
BBB
AAA
AAA
AAA
C
1
2221
1111
21
21
11211
MMM
LL
LL
L
MMM
L
MMM
L
The inner dimension n of A and B must be the same.
MATLAB CODE --- BRUTE FORCE
[m, n] = size(A); [n, p] = size(B);
C = zeros(m, p);
for j = 1:p
for i = 1:m
for k = 1:n
C(i, j) = C(i, j) + A(i, k)*B(k, j);
end
end
end
pf3
pf4
pf5

Partial preview of the text

Download Matrix Multiplication: Inner Product and Outer Product - Prof. Marc Smith and more Study notes Computer Science in PDF only on Docsity!

MATRIX MULTIPLICATION

C = A*B Def: Cij =∑ k^ n = 1 AikBkj

The matrix sizes are: A is m x n, B is n x p, C is m x p.

Sum the elements multiplied by the elements of this row of this column.

n nj np

j p

j p

m m mn

i i in

n

B B B

B B B

B B B

A A A

A A A

A A A

C

1

21 2 2

11 1 1

1 2

1 2

11 12 1 M M M

L L

L L

L

M M M

L

M M M

L

The inner dimension n of A and B must be the same.

MATLAB CODE --- BRUTE FORCE

[m, n] = size(A); [n, p] = size(B); C = zeros(m, p); for j = 1:p for i = 1:m for k = 1:n C(i, j) = C(i, j) + A(i, k)*B(k, j); end end end

INNER PRODUCT

The product for each Cij is the inner product or dot product of a row vector and a column vector

MATLAB CODE

[m, n] = size(A); [n, p] = Size(B); C = zeros(m, p); for j = 1:p for i = 1:m C(i, j) = A(i, :)*B(:, j); end end

COLUMN–ORIENTED VERSION

When C is a 2-D matrix: C (:, j ) =∑ k^ n = 1 A (:, k )* B ( k , j )

MATLAB CODE

[m, n] = size(A); [n, p] = size(B); C = zeros(m, p); for j = 1:p for k = 1:n C(:, j) = C(:, j) + A(:, k)*B(k, j); end end

or on another level

[m, n] = size(A); [n, p] = size(B); C = zeros(m, p); for j = 1:p C(:, j) = A*B(:, j); end

OUTER PRODUCT

[ n ]

m

T (^) v v v u

u

u uv (^) M^2 12 L

1 ∗ 

m m m n

n

n

u v u v u v

u v u v u v

uv uv uv

L

M M L M

L

L

1 2

2 1 2 2 2

1 1 1 2 1

Emphasize row structure of the product: i-th row = ui vT

m m m n

n

n

m T

T

T T u v u v u v

u v u v uv

uv uv uv

u v

u v

uv uv L

M M L M

L

L

M

1 2

2 1 2 2 2

1 1 1 2 1 2

1

Emphasize column structure of the product j-th column = uvj

[ ]

m m m n

n

n T n u v u v u v

uv u v u v

uv uv uv uv uv uv uv L

M M L M

L

L

L

1 2

2 1 2 2 2

1 1 1 2 1 1 2

C = A*B -- AN INNER PRODUCT OF OUTER

PRODUCTS

C =[ A^ (:,^1 )^ A (:,^2 )^ L A (:,^ n )]

B n

B

B

M

= ∑ k^ n = 1 A (:, k ) ∗ B ( k , :)

MATLAB CODE

[m, n] = size(A); [n, p] = size(B); C = zeros(m, p); for k = 1:n C = C + A(:, k)*B(k, :); end

or on another level

C = A*B;