%% Programming Languages Matlab 3101 - Class 1 % 3/5/08, Instructor: Blake Shaw %% Overview % Matlab as a calculator: mathematical functions, arrays, array operations, % matrices, simple plotting tools, running script files %% How to get help % help and doc help sin doc sin %% Matlab as a calculator % do some math! a = 2 + 3 + 4 a = 3.156 %% Mathematical functions % abs, factor, factorial, abs(-10 * a) %% Working with variables % declare variables, use them in equations, semi-colon suppresses output a = 3; b = 4; c = sqrt(a^2 + b^2) %% Using scripts -- running commands listed in a file % show how to make comments, use cell mode, cd into directory and run a % file %% Working with arrays % make an array from a list of numbers, and do some math on it p = [1, 4, 5, 6, 8] p * 2 factorial(p) %% Element wise operations with arrays % .* and * are different, this is tricky! p .* p p .^ 2 %% Useful functions for working with arrays % get the size of it, access elements of it, concatenate arrays remove % elements p size(p) p(3) p2 = [p, 3] p4 = [1, p, p, 5] p(1) = []; %% Indexing mutliple items in a arrays with the colon operator % the colon operator is great for indexing... really great... 1:5 10:20 100:105 p(2:4) p([2, 3, 4]) %% Different ways to index % binary vector, using end, different increments 10:-1:1 x = 2:7:20; size(x) i = logical([1, 0, 1]); x(i) isprime(x) %% You can apply mathematical functions to arrays % more then just plus and minus p + 3 p.^2 + 10 %% Other useful functions with arrays % sum, max, min, length, sort, mean, std, whos, clear, size sum(p) max(p) min(p) t = [-5, 6, 4, 2, 9, 1, 2, 4]; mean(t) std(t) sort(t) %% Numbers, Arrays, and Matrices... all the same % just different sizes... A = [1, 2; 3, 4] %% Can do math with matrices % simple stuff like plus and minus, more complicated stuff like inverse, % transpose, eig, diag, A .^ 2 B = [A.^2, A.^3; A.^4, A.^5] a =1:5 C = [a; a.^2; a.^3] %% Generating arrays and matrices % colon is great, but also there is rand, ones, zeros, eye, etc... D = rand(5, 5) D = ones(5, 5) D = zeros(5, 5) D = eye(5, 5) %% Let's plot some stuff, it's easy! % some basics of plotting, plot, hist, bar, pie x = 1:1000; y = x.^2; x(1:5) y(1:5) plot(y) %% plotting sin x = -pi:(pi/1000):pi; y = sin(x); size(x) plot(y) %% histograms a = floor(100*rand(100, 1)) plot(a) hist(a, 20) %% bar and pie plots r = rand(10, 1) sum(r) r2 = r ./ sum(r) sum(r2) r3 = sort(r2, 'descend') figure(1); bar(r3) title('my bar plot'); figure(2); pie(r3) title('my pie plot'); %% More notes N = 5; b = 1:N b * b' b' * b A = b' * b A = round(10*rand(N, N)) Atrans = A' Ainv = inv(A) A * Ainv [v, d] = eig(A); diag(d) x = 4:3:23; diag(x) diag(diag(x)) x