Created
February 16, 2020 10:47
-
-
Save dapperfu/4215928615caebf26daa471369506ecd to your computer and use it in GitHub Desktop.
Learning Matlab through Algebra examples.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% Multiplying a Matrix by Another Matrix | |
% https://www.mathsisfun.com/algebra/matrix-multiplying.html | |
% But to multiply a matrix by another matrix we need to | |
% do the "dot product" of rows and columns ... | |
% what does that mean? Let us see with an example: | |
% Method 1: Using MATLAB. | |
A = [1 2 3 | |
4 5 6] | |
B = [7 8 | |
9 10 | |
11 12] | |
C = A * B | |
[A_rows, A_columns] = size(A) | |
[B_rows, B_columns] = size(B) | |
% Method 2: | |
% Matrix result has this shape. | |
% help zeros | |
C2 = zeros(A_rows, B_columns) | |
% Loop through each row, using the dot product. | |
for A_row_index = 1:A_rows | |
fprintf('Calculating A Row %d\n', A_row_index) | |
% And through each column. | |
for B_column_index = 1:B_columns | |
fprintf('Calculating B Column %d\n', B_column_index) | |
% To calculate the result. | |
row = A(A_row_index,:) | |
column = B(:, B_column_index) | |
% The | |
C2(A_row_index, B_column_index) = dot(row, column) | |
end | |
end | |
% Method 3: | |
% Loops on loops. | |
C3 = zeros(A_rows, B_columns) | |
% Loop through each row, using the dot product. | |
for A_row_index = 1:A_rows | |
fprintf('Calculating A Row %d\n', A_row_index) | |
% And through each column. | |
for B_column_index = 1:B_columns | |
fprintf('Calculating B Column %d\n', B_column_index) | |
% To calculate the result. | |
row = A(A_row_index,:) | |
column = B(:, B_column_index) | |
assert(length(row)==length(column)) | |
accumulator = 0 | |
for index = 1:length(row) | |
Number1 = row(index) | |
Number2 = column(index) | |
% Other languages have += operators: | |
% accumulator += Number1*Number2 | |
accumulator = accumulator + Number1*Number2 | |
C3(A_row_index, B_column_index) = dot(row, column) | |
end | |
end | |
end | |
assert(all(all(C==C2))) | |
assert(all(all(C==C3))) | |
assert(all(all(C2==C3))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment