clear
% Math 471 (Sec 001) Fall 2013
%
% Pete Bosler
% August 20, 2013
%
%% MATLAB SCRIPT EXAMPLE
%
% The percent '%' character is the comment marker in Matlab.
% Everything that follows the '%' character will be ignored by the
% software.
%
% Comments that follow a '%' sign are useful for describing what your
% code does, what each variable represents, and dividing sections of code
% into a readable outline.
%
% Two percentage characters in a row '%%' create a Matlabe code cell.
% Cells may be executed individually and Matlab automatically creates an
% outline of your code using cells.
%
% PROBLEM : Use Matlab to find the sum of consecutive positive integers
% from 1 to N, where N is a variable supplied by a user.
%
%
% To get familiar with Matlab, we will compute the sum of consecutive
% integers in three different ways.
%% User Input section
N = 100; % A semicolon at the end of each line suppresses that line's output
%% Method 1 : A 'for' loop
start1 = tic; % the 'tic' command starts a timer
s1 = 0; % variable where sum will be stored
for j=1:N % j is a loop variable; it starts with the value 1 and
s1 = s1 + j; % increments over each integer up to and including N.
end
toc(start1); % the 'toc' command stops the timer started with 'tic'
% (tic and toc must always be paired).
answer1string = ['Method 1: sum = ',num2str(s1)]; % Join strings of characters
% with square brackets.
% NOTE :
%
% Matlab documentation is available from the 'Help' menu; select either
% 'Documentation' or 'Product Help' for a searchable list of every Matlab
% command. Open help and Search for 'num2str' to acquaint yourself with
% this function.
disp(answer1string); % 'disp' writes its argument to the command window console.
%% Method 2 : Matlab arrays
% Matlab's basic data type are double-precision arrays (matrices) of
% complex numbers. As a consequence, many of its operations may be sped up
% by writing them in array form, rather than as 'for' loops.
start2 = tic;
integers = 1:N; % creates an array of integers from 1 to N
s2 = sum(integers);
toc(start2);
answer2string = ['Method 2: sum = ',num2str(s2)];
disp(answer2string);
%% Method 3 : A fast formula
start3 = tic;
s3 = N*(N+1)/2;
toc(start3);
answer3string = ['Method 3: sum = ',num2str(s3)];
disp(answer3string);