Skip to content

Instantly share code, notes, and snippets.

@dapperfu
Created Feb 16, 2020
Embed
What would you like to do?
Learning Matlab through Algebra examples.
%% 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