Matrix Addition and Multiplication
Scalar Multiplication/Division, Addition/Subtraction
If we multiply a matrix by a number, we multiply every element of that matrix by that number. Addition, subtraction, and division of a matrix with a sclar value work the same way
matA = rand(3,2)
0.3111 0.1848
0.9234 0.9049
0.4302 0.9797
c*matA
3.1110 1.8482
9.2338 9.0488
4.3021 9.7975
matA/c
0.0311 0.0185
0.0923 0.0905
0.0430 0.0980
matA - c
-9.6889 -9.8152
-9.0766 -9.0951
-9.5698 -9.0203
matA + c
10.3111 10.1848
10.9234 10.9049
10.4302 10.9797
Addition and Subtraction
You can add/subtract together two matrixes of the same size. We can add up the two 3 by 1 vectors from above, and the two 2 by 3 matrixes from above.
matA = rand(3,2)
0.6028 0.1174
0.7112 0.2967
0.2217 0.3188
matB = rand(3,2)
0.4242 0.2625
0.5079 0.8010
0.0855 0.0292
matA - matB
0.1787 -0.1451
0.2034 -0.5043
0.1362 0.2896
When using matlab, even if you add up to a single column or single row with a matrix that has multiple rows and columns, if the column count or row count matches up, matlab will broadcast rules, and addition will still be legal. In the example below, matA is 3 by 2, and colVecA is 3 by 1, matlab duplicate colVecA and add it to each column of matA (Broadcast rules are important for efficient storage and computation):
matA + colVecA
1.0417 0.5563
0.8223 0.4078
0.4798 0.5768
Matrix Multiplication
When we try to multiply two matrixes together:
for example, the number of columns of matrix A and the number of rows of matrix B have to match up. If the matrix A is has L rows and M columns, and the matrix B has M rows and Ncolumns, then the resulting matrix of
has to have L rows and N columns. Each of the
cell in the product matrix
, is equal to: Note that we are summing over M: row l in matrix A, and column n in matrix B both have M elements. We multiply each m of the M element from the row in A and column in B together one by one, and then sum them up to end up with the value for the lth row and nth column in matrix C.
% (3 by 4) times (4 by 2) end up with (3 by 2)
matA = rand(L, M)
0.9289 0.5785 0.9631 0.2316
0.7303 0.2373 0.5468 0.4889
0.4886 0.4588 0.5211 0.6241
matB = rand(M, N)
0.6791 0.0377
0.3955 0.8852
0.3674 0.9133
0.9880 0.7962
matC = matA*matB
1.4423 1.6111
1.2738 1.1262
1.3214 1.3974
% (2 by 10) times (10 by 1) end up with (2 by 1)
matA = rand(L, M)
0.0987 0.3354 0.1366 0.1068 0.4942 0.7150 0.8909 0.6987 0.0305 0.5000
0.2619 0.6797 0.7212 0.6538 0.7791 0.9037 0.3342 0.1978 0.7441 0.4799
matB = rand(M, N)
0.9047
0.6099
0.6177
0.8594
0.8055
0.5767
0.1829
0.2399
0.8865
0.0287