% Five different ways of adding all integers from 1 to 100. Surely, there are more. 
% Feel free to add your own way.
%
% Intro to Matlab programming 5110 SU13
% Andres Patrignani and Tyson Ochsner.
% Soil Physics, OSU.
%% Answer 1
answer1 = sum(1:100)

%% Answer 2
answer2 = 50 * 101; % 1+100=101, 2+99=101, 3+98=101...and so on.

%% Answer 3
answer3 = zeros(50,1); % Pre-allocate memory.
for n = 1:50;
answer3(n) = 100 - n + n + 1; % the same pattern as before coded differently.
end
answer3 = sum(answer3);

%% Answer 4
answer4 = 100 + sum(45 + 100 .* (0:9)); % 45 is the sum from 0 to 9, 145 is 
% the sum from 10 to 19, 245 is the sum from 20 to 29... and so on.

%% Answer 5
answer5 = zeros(49,1); % Pre-allocating memory.
for i= 1:49
   answer5(i) = i + (100-i ); % last calculation of the loop will be: 49 + (100-49), therefore 50 was left out as well as 100.
end

answer5 = sum(answer5) + 50 + 100; % See that 50 and 100 were left out before.

%% Sum is one of the fastest functions
tic; % Start timing the function
SumIsReallyFast = sum(1:10e6);
SumTime = toc; % Finish timing the function.
fprintf ('For Matlab, to sum from 1 to 1,000,000 only takes %.2f seconds\n',SumTime);
