% This is a comment in an m-file. % This m-file is an introduction to working with matrices; it is % organized into cells. clear % Clear all variables to start fresh %% Using help help \ %% This is a cell break so we can evaluate our m-file step by step 2+2 % result is saved to default variable 'ans' %% Assignments to variables x = 2+2 %% Assign result to variable x y = 2^2 + log(pi) * sin(x) / (1-exp(-x^2)) * erf(-0.01); % ';' suppresses output, use of built-in functions %% Change floating point number display format format long y format long e y format short e %% Complex numbers %% c1=exp(pi/4*i) c2=exp(pi/4i) % What is the difference? c3=(1+3i)/(1-3i) %% Vectors and Arrays %% x = [1 2 3] % Re-define x as a [1x3] matrix (i.e. a vector) y = [1; 2; 3] % Re-define y as a [3x1] matrix %% b = x + [2 1 0] % Can add (or subtract) two matrices of same size b = x + y % This doesn't work! %% size(x) size(y) %% Multiply two vectors of same size element by element z = [3 2 -1]; a = x.*z %% Multiply by a scalar b = 2*a %% Matrices %% Explicit defintion of a [2x3] matrix d = [1 2 3 ; 4 5 6] %% Transpose of a matrix d.' %% Building matrices from matrices d = [x ; z] % [2x3] matrix d = [x z] % Concatenation, [1x6] matrix d = [[x ; z] [x ; z] ; [3 4 5 -3 2 1]] % A more complicated example! %% Building a tridiagonal matrix g = [2 4 6 8] g1 = [-2 3 4] g2 = [1 -2 7] G = diag(g) + diag(g1,1) + diag(g1,-1) %% Identity matrix eye(3,3) %% Random matrix (uniformly distributed) d = rand(6,8) %% Ones matrix ones(3,3) %% Zeros matrix zeros(3,3) %% Linearly space vectors x = linspace(0,10,6) x = [0:2:10] %% Parts of matrices element = d(3,4) % An element row = d(2,:) % An entire row column = d(:,2) % An entire column part1 = d(3:5, 4:5) % A sub-section part2 = d(2,[2 3]) % Another sub-section diagonal = diag(d) % The diagonal upper = triu(d) % Upper triangle lower = tril(d) % Lower triangle %% Finding the the last element of a matrix x(end) %% Deleting a row or column dd = rand(5,7) dd(2,:) = [] % Deletes second row of dd dd(:,3:5) = [] % Deletes 3rd to 5th columns of dd %% Operations on matrices %% Matrix multiplication e = rand(8,6); matrix_mult = d*e %% Term by term multiplication term_mult = d.*e.' %% Term by term division term_div = d./e.' %% Element functions operate term by term z = sqrt(d)*e %% Raising to a power z_square = z.^2 % Term by term z_times_z = z^2 % %% Inverse of a matrix inv(z) z*inv(z) % Check! eps % Machine epsilon %% Various built-in matrix functions max(z) %% max(max(z)) %% min(z) %% min(min(z)) %% sum(z) %% sum(sum(z)) %% Finding out properties of current variables whos % All variables whos d % A particular variable %% Clear a variable from memory clear d whos d %% Clear all variables clear whos