function matprod
% MATLAB demo: Various ways to implement to matrix product
A = rand(5,5); B = rand(5,5); % Initialize random matrices
C1 = mlmatprod(A,B);    % MATLAB matrix multiplication
C2 = loopmatprod(A,B);   
C3 = dotmatprod(A,B);
norm(C1-C2), norm(C3-C2), % Check agreement of results

end

% Standard matrix product in MATLAB
function C = mlmatprod(A,B)
    C = A*B; 
end

% Nested loop implementation of matrix multiplication
function C = loopmatprod(A,B)
  [n,k] = size(A); % A is an $n\times k$-matrix
  [kb,m] = size(B); % B is an $k\times m$-matrix
  if (k ~= kb), error('Mismatch of matrix dimensions'); end
  C = zeros(n,m);
  for i=1:n
     for j=1:m
         C(i,j) = 0;
         for l=1:k
             C(i,j) = C(i,j)+ A(i,l)*B(l,j);
         end
     end
  endw
end
  
% Direct computation of entries of C by forming scalar products of columns
% of $\VB$ and rows of $\VA$.
function C = dotmatprod(A,B)
  [n,k] = size(A); % A is an $n\times k$-matrix
  [kb,m] = size(B); % B is an $k\times m$-matrix
  if (k ~= kb), error('Mismatch of matrix dimensions'); end
  C = zeros(n,m); % Mainly allocate memory for matrix
  for i=1:n
    for j=1:m
      % Note: access to rows and columns through range operator :
        C(i,j) = dot(A(i,:),B(:,j)); 
    end
  end
end


