% Exercises from the sixth session (26.11.2015)

%%
% 1: Using for loops, calculate the volumes of cilinders whose radii are
% r={1,1.2,1.3} and whose height is h = 5. That is, calculate three volumes
% (one for each cilinder). Write these volumes to a vector V.
% The volume of a cilinder is given by V = pi r^2 h;

% First, we set up a vector with the radii, as well as the height.
h = 5;
r = [1,1.2,1.3];

% Now, we create a For loop with an index i that goes from 1 to the size of
% r. Done like this, you can use any number of elements in r without having
% to rewrite it. If you don't know what the function 'numel()' does, use
% the help file. Additionally, we initialize the vector V with all zeroes.
% It is not necessary, but good practice to make the code run faster. The
% size of V will be the same as the size of r.

v = zeros(1,numel(r));
for i = 1:numel(r)
    v(i) = pi*h*(r(i)^2);
end

display(v)

% Notes: we want every execution of the code inside the For loop to be done
% with one of the components of r. That is why we use r(i).

%%
% 2: Repeat the previous exercise, but now with r = {1,1.2,1.3} and h =
% {5,10,12}. Write the results to a 3x3 matrix. Hint: use two nested For
% loops.

% Note: Use different variable names as in the previous exercise. Here I
% will use the Upper case versions.
% Note: As in class, I will do the exercise with h = {5,10,12,15} instead,
% to make it clearer.

R = [1,1.2,1.3];
H = [5,10,12,15];

V = zeros(numel(R),numel(H)); % Each row is a Radius, each column a Height.

% Now, as the hint says, we will have two For loops, one inside of the
% other. The first loop will go through each component of R, the second
% loop will go through each component of H.

for i=1:numel(R)
    for j=1:numel(H)
        V(i,j) = pi*H(j)*(R(i)^2);
    end
end
display(V)
% A bit of an explanation as to how this works: In line 49, i is set to 1
% (i=1), then it jumps to line 50, where j = 1; then, line 51 is executed
% with these values and the result saved in V(1,1). The END in line 52 is
% reached, and then the execution goes back to line 50, where j is set to 2
% and i remains unchanged. V(1,2) is calculated. In the same fashion,
% V(1,3) is calculated, then V(1,4) and this is where the inside loop (with
% index j) ends. Finally, the END in line 53 is reached, and the execution
% jumps back to line 49, where now i is set to 2. In line 50 j is set to 1,
% and now the values V(2,1), V(2,2), V(2,3) and V(2,4) are calculated. Then
%, in line 49 i is set to 3, and the values V(3,1), V(3,2), V(3,3) and
%V(3,4) are calculated. This is now the end of the outter loop and the
%execution finally continues to the display(V).

% Note that the first column of V has the same values as v from the
% previous exercise. That is, V(1,:)' == v;

%%
% 3: We will solve this one in the next session.


