Solutions

Use of Operations

The commands you entered into the command line should look something like this:

In [10]:
x = [0; -2; 3];
y = [-1; 3; 2];
z = [13; 3; 2];
fprintf('x .* y: \n')
disp( sum(x .* y) )
fprintf('x .* z: \n')
disp( sum(x .* z) )
fprintf('y .* z: \n')
disp( sum(y .* z) )
M = [x y z];
b = ones(3,1);
w = M\b;
fprintf('Solution w: \n')
disp(w)
x .* y: 
0
x .* z: 
0
y .* z: 
0
Solution w: 
   0.076923
   0.285714
   0.098901

Constructing a Finite Difference Matrix

We can use diag in a number of ways - in this case, we are going to give it a vector of values, and ask it to construct 3 matrices for us. Then, we will add those matrices together to produce FEM_N.

In [12]:
% NOTICE that anything after a % on a line is not read by MATLAB. 
% These are called comments, and are a useful tool to remind you what your code is meant to be doing!
N = 5; %it always helps to generalise your code where possible!
%first, we need to construct a matrix with 2's on the leading diagonal
diag_entries = 2*ones(1,N); %this is a vector of 2's of the same length as the diagonal of the matrix we want to construct.
diag_mat = diag(diag_entries); %this is now an N-by-N matrix with 2's on the main diagonal.
%now we construct matrices with -1 on the super- and sub-diagonal
off_diag_entries = -1*ones(1,N-1); %read the help for diag carefully. The super- and sub- diagonals are of length N-1, so we need a vector of this length.
super_diag_mat = diag(off_diag_entries,1); %-1's on the superdiagonal, using diag's optional argument
sub_diag_mat = diag(off_diag_entries,-1); %-1's on the subdiagonal, using diag's optional argument
%now we put it all together
FEM_N = diag_mat + super_diag_mat + sub_diag_mat; %all other entries are 0s, so there's no problems with crossover.
fprintf('Here''s what the code put together:\n') %double '' in strings is used for an apostrophe
disp(FEM_N)
Here's what the code put together:
   2  -1   0   0   0
  -1   2  -1   0   0
   0  -1   2  -1   0
   0   0  -1   2  -1
   0   0   0  -1   2