% Matlab program slow_program.m
% Written by Todd M. Bezenek
% University of Wisconsin at Madison
% October 16, 1996

% These Matlab commands demonstrate that not writing Matlab programs
% carefully can cause a significant slow-down in their execution times.

% This example is rather "contrived", but the intent is to show what can
% happen using an easily understood example.
 
% Two 50 x 50 matrices are multiplied twice.  One time using the
% matrix multiply operator, and one time by implementing the operation
% with a simple program.  Both versions of the program perform exactly
% the same calculations.  The first does the calculations internally and
% the second does them explicitly, with the Matlab interpreter having to
% loop through the user program many times.

% Clean out everything.
clear;

% This defines the size of the matrices to be used.
SIZE = 50;

% Set up a couple of random matrices.
A = rand(SIZE,SIZE);
B = rand(SIZE,SIZE);

% Multiply them using Matlab's matrix multiplication operator.
fprintf('Using the first method, please wait...');
tic;
C1 = A * B;
toc

% Multiply them using an explicit program.
fprintf('Using the second method, please wait...');

% This creates the result matrix.  It is not needed, but it makes me feel
% better.
C2 = zeros(SIZE,SIZE);

% Go through the result matrix, computing each value.
tic;
for result_row = 1:SIZE,
  for result_col = 1:SIZE,

    % To find an element of the result...
    sum = 0;
    for n = 1:SIZE,
      sum = sum + A(result_row, n) * B(n, result_col);
    end
    C2(result_row, result_col) = sum;

  end
end
toc

% Make sure the results agree.
if (C1 == C2)
  fprintf('The two routines gave the same result.\n');
else
  fprintf('The two routines gave different results.\n');
end

