%Exercises of session 2

%% Exercises with matrices
%Define the three vectors:
A = 2:2:20;
B = -21:-12;
C = zeros(1,10);

%Create a matrix MatX whose rows are A, B and C, in that order:
MatX = [A;B;C]; %note the use of ; instead of ,

%Read out all elements of the second row of MatX
MatX(2,:)

%Read out the first five elements of rows one and two
MatX([1,2], 1:5) % = (1:2, [1,2,3,4,5]) etc.

%Replace the second column of MatX with zeroes using the command
%zeroes(a,b)
MatX(:,2) = zeros( size(MatX,1), 1) %neat trick with size!

%Replace the element in the second row, third column, with -Inf
MatX(2,3) = -Inf; % = -inf    (inf and Inf are the same in matlab)

%Create a matrix A = magic(5). Obtain the sum of the elements of each
%column and row separately
%To obtain sum of row 1, for example:
SumRow1 = sum(MatX(1,:)); % = MatX(1,1) + MatX(1,2) + ... 
%For a column:
SumCol1 = sum(MatX(:,1));
% Any guess what sum(MatX,1) and sum(MatX,2) do?

%Create a matrix MatY that is MatX with an extra column at the end. This
%extra column should be populated with the sum of each corresponding row.

%For those who want to be very clear:
MatY = [ [MatX(1,:), sum(MatX(1,:))]; [MatX(2,:), sum(MatX(2,:))]; ...
    [MatX(3,:), sum(MatX(3,:))]];
%Notice that you can break a command into two lines with those 
%elipsis (...) at the end.

%For the frugal ones:
MatY2 = [ MatX, sum(MatX,2)];
%Both result on the same MatY, but the second one is more wieldly when MatX
%has many columns.


%%Matrix operation exercises

%Define the matrices:
MatX = [3 1 -5; 10 -1.2 0];
VecX = [-1 100 3];
%Notice the lack of commas. Matlab doesn't care about those, but ; are
%absolutely necessary.

%Create a matrix MatY, whose first row is the first of MatX multiplied by
%5, and whose second row is the second row of MatX multiplied by 7
MatY = [ 5*MatX(1,:); 7*MatX(2,:)];

%Multiply VecX and MatX.
%There are a couple of possibilities:
TheFirstOne = MatX*VecX';
TheSecndOne = VecX*MatX';
%Then of course, TefirstOne = TheSecndOne'.

%Multiply MatX with itself.
%If MatX were square (that is, same number of rows as columns), then
%MatX*MatX would work (and also MatX^2). Not being the case:
MultiMatX1 = MatX*MatX';
MultiMatX2 = MatX'*MatX;
%Curiously, they're the same.

