% Unit 2 (MATLAB Course @ UAM)
% (c) Alexander Knebe

%===================================================================
% mathematical matrix multiplication  C(i,j) = sum_k A(i,k).*B(k,j)
%===================================================================
clear all
close all
clc

disp('===================================================================')
disp(' matrix multiplication')
disp('===================================================================')
A = [1,2; 3,4; 5,6];
B = [7,8,9; 10,11,12];

% or maybe play a bit with random matrices:
%A = rand(7,4);
%B = rand(4,3);

% get matrix dimensions of A
sA=size(A);
disp('number of rows in A:')
m=sA(1)
disp('number of columns in A:')
n1=sA(2)

% get matrix dimensions of B
sB=size(B);
disp('number of rows in B:')
n2=sB(1)
disp('number of columns in B:')
k=sB(2)

% check if we can actually calculate the product
% Note: this check uses the advanced command 'if'
if n1 ~= n2
    disp('problem with matrix dimensions')
end

% generate a new matrix of the correct size
C = zeros(sA(1),sB(2));

% perform the nested loop multiplying both matrizes
for i=1:sA(1)
    for j=1:sB(2)
        for k=1:sA(2)
            C(i,j) = C(i,j) + A(i,k).*B(k,j);
        end
        % one could also do it like this in MATLAB, avoiding the inner-most for-loop over k
        % C(i,j) = sum( A(i,:).*B(:,j) );
    end
end

disp('the matrix product is:')
C

disp('the matrix product using the * operator is: ')
A*B

disp('the difference between the two resulting matrizes is:')
C-A*B


