
Matrix Operations
Matrices are multi-dimensional collections of numbers that are used to represent properties of an entity or object in mathematics and linear algebra. The following is an example of a 3 x 2
matrix:
Matrix Addition
Matrices can be added with other matrices of the same size only. Adding matrices involves adding their individual elements together.
Matrix Multiplication
Matrices can also be multiplied together if their sizes are compatible. A matrix of size a x b
can be multiplied to a matrix of size c x d
if and only if b = c
, and will result in a matrix of size a x d
. So, for example, a matrix of size 3 x 2
can be multiplied to a matrix of size 2 x 5
to form a matrix of size 3 x 5
. However, a matrix of size 3 x 2
cannot be multiple to a matrix of size 5 x 3
.
Let's work out the multiplication of matrices and
(i.e.
) as given below:
is a
3 x 2
matrix, and is a
2 x 2
matrix. Because the number of columns in is equal to the number of rows in
, this multiplication is possible. The resulting matrix will be of size
3 x 2
:
We start by taking the first row of and the first column of
:
We can multiply these two set of numbers in an element-wise manner and add them together:
This operation is known as the dot product and gives us the top left element of our resulting matrix:
We can continue this for all pairs of rows in and columns in
to get the final result of multiplication:
Exercise
Write a program that takes three matrices ,
, and
, and performs the following operation:
In other words, multiply with
, then add
.
Remember to check if the sizes of the matrices are valid. If the sizes are not compatible, raise numpy.linalg.LinAlgError
.
Sample Test Cases
Test Case 1
Input:
[
[[ 9,-3],
[ 2, 2],
[-8, 5]],
[[ 0, 0],
[ 0, 0],
[ 0, 0]],
[[ 1, 2],
[-5,-3]]
]
Output:
[[ 24, 27],
[ -8, -2],
[-33, -31]]
Test Case 2
Input:
[
[[ 9, -3],
[ 2, 2],
[-8, 5]],
[[12, 3],
[-1, -6],
[ 0,-18]],
[[ 1, 0],
[ 0, 1]]
]
Output:
[[ 21, 0]
[ 1, -4]
[ -8, -13]]
Test Case 3
Input:
[
[[ 9, -3],
[ 2, 2],
[-8, 5]],
[[12, 3],
[-1, -6],
[ 0,-18]],
[[ 1, 2],
[-5, -3]]
]
Output:
[[ 36, 30],
[ -9, -8],
[-33, -49]]
Test Case 4
Input:
[
[[ 2, 9],
[ 0, -2]],
[[19, 5, 7],
[-4, 3, 12]],
[[ 8, 9],
[ 1, -9]]
]
Output:
LinAlgError()
Test Case 5
Input:
[
[[ 2, 9],
[ 0, -2]],
[[19, 5],
[-4, 3]],
[[ 8, 9, -4],
[ 1, -9, 6]]
]
Output:
LinAlgError()