%% Theory0: % MSc MATLAB Crash Course: Basic operations with the command window. % % Originally written by Nick Hale, Oct. 2013. % Extended by Asgeir Birkisson, Oct. 2014, 2015. % Modified by Behnam Hashemi and Hadrien Montanelli, Sep. 2016. %% First steps 5 + 10 3 - 2 3*2 3/2 3^2 exp(3) sqrt(9) factorial(5) sin(3) sin(pi) sind(90) %% Get help help sin doc sin %% Initialize vectors a = [1 3 5] % Row vector a = [1, 3, 5] % The same size(a) % Size of a length(a) % max of the above a = [1 ; 3 ; 5] % Column vector size(a) % Size of a a = [1+1i 3 5] % Column vector with complex entries a = [1+1i 3 5].' % .' gives the transpose a = [1+1i 3 5]' % ' gives the conjugate transpose %% Simple commands clc % clear command window a max(a) % Maximum value min(a) % Minimum value sum(a) % Sum of entries mean(a) % Average value %% Addition and multiplication b = [2 6 10]'; % Another column vector c = a + b d = 4*a e = 3*a + 5*b; %% Modifying a vector a a(2) = 11 % Modify second entry a = [a; 4] % Add an entry at the end a = [7; a] % Add an entry at the start a(3) = [] % Remove the third entry %% Vector syntax 1:100 1:5:101 10:-2:0 linspace(0, 1, 51) %% Initialise a matrix A = [1 8; 5 2] % 2x2 matrix A' % (Conjugate) Transpose of the matrix size(A) length(A) %% Simple commands -- acting columnwise max(A) min(A) sum(A) mean(A) %% Simple commands -- acting rowwise % Notice extra arguments to the function max(A, [], 2) min(A, [], 2) sum(A, 2) mean(A, 2) %% Addition and multiplication B = [4 5; 9 3]; % Another 2x2 matrix C = 3*A + B %% Matrix syntax A(1, 2) A(:, 2) A(1, :) D = diag(A) % Diagonal elements det(A) %% Useful commands A = rand(3, 3) % matrix with random elements A = rand(3) % the same O = ones(3) % matrix with ones Z = zeros(3) % matrix with zeros %% Factorizations A = rand(5) [V, D] = eig(A) % Eigenvectors and eigenvalues [L, U, P] = lu(A) % LU decomposition [Q, R] = qr(A) % QR factorisation Q*Q' %% Solve a linear system -- Ax = b % Solve % x1 + 2*x2 = 1 % 5*x1 + 8*x2 = 2 A = [1 2; 5 8]; b = [1 2]'; x = A\b % Use backslash for solving x = inv(A)*b; % This is not good -- numerical instabilities % Solve with random coefficients and right-hand side: A = rand(2, 2); b = rand(2, 1); x = A\b %% Formats pi format long pi % Format does NOT affect how Matlab computations are done, just the display format short a = sqrt(2) format long b = sqrt(2) a - b % Get rid of extra linespaces format compact a - b % Reintroduce the extra linespaces format loose a - b %% Basic plotting x = linspace(-1, 1, 100); plot(x, sin(4*pi*x)) %% hold on plot(x, exp(cos(10*x)), 'r') hold off %% Tidying up close who whos clc a = 4; b = 5; clear a clear all