% Matlab Lesson I % A PHYS 451/551 I CSI 451/551 % Kevin Knuth % 18 Sept 2006 % IDE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Command Window % Workspace % Command History % Current Directory % Editor % Matlab stands for Matrix Laboratory % Matlab is FAST when it comes to matrix computations % TIME %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % How to measure program run time tic toc % Try this several times % Sometimes it takes a little longer. % Your computer is off doing other things! % NUMERIC VARIABLES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% a = 0.1234567890; % notice that the variable appears in the Workspace % notice that it is rounded to the nearest 0.001 % can be changed using 'format' % note that the variable's PRECISION is NOT reflected in the display help format format long disp(a) % disp displays the variable help disp doc disp % PRECISION %%% % search for 'Floating-Point Numbers' in doc doc % DATA TYPES %%% % search for 'Data Types' doc % double-precision will usually be sufficient for our needs % OPERATIONS %%% b = 123.0; % Note that the ; suppressed output. c = a + b d = a - b; d e = a * b; e = a*b; f = a/b; g = a^b; % SPECIAL NUMBERS %%% % imaginary i % UNLESS YOU HAVE DEFINED IT AS AN INTEGER i i = 2 sqrt(-1) i % e exp(1) % pi pi % MATRICES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % clear the Workspace clear; a = [1, 2; 3, 4] b = [1; 1] c = a * b % How fast was that??? tic; c = a*b; toc; % Let's make a bigger matrix A = [ 1, 2, 3; 4, 5, 6; 7, 8, 9] % How do we access the element in the 3rd row and 1st column? A(3,1) % How do we access the entire second row? A(2,:) % How do we access the entire third column? A(:,3) % SPECIAL MATRIX COMMANDS % identity matrix I = eye(5) % ones W = ones(2,5) % zeros Z = zeros(10,1) % uniformly distributed random numbers between 0 and 1 r = rand(1,10) % oops long format! format short disp(r) % normally distributed random numbers with mean 0 and var 1 n = randn(1,3000); disp(n) % now you can see why we might supress output % we can estimate its mean and variance mean(n) var(n) stddev = sqrt(var(n)) % an array of counting numbers from 5 to 10 C = 5:10 C = [5:10] % an array from 5 to 10 stepping by 0.5 D = [5:0.5:10]; disp(D) % most common error disp(A) X = [1 2 3]; Y = A*X % oops % look at Workspace % or type whos % A is 3x3, but X is 1x3 % X needs to be 3x1 % transpose disp(X) T = X'; disp(T) Y = A*X' % inverse invA = inv(A) % oops! % badly conditioned...check its determinant!!! det(A) % try this instead B = round(10*rand(3,3)) % what did this do??? det(B) inv(B) % sizes disp(X) size(X) length(X) disp(T) size(T) length(T) disp(B) size(B) length(B) % what is length doing??? disp(W) size(W) length(W) length(W') % BASIC FIGURES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear; % Earlier we made an array of consecutive numbers t = 1:0.01:5; % this is a lot of numbers! size(t) % I often use uppercase variables for counts of things T = length(t) % lets make a sine wave % A sin (2 pi f t) % we will let amplitude be A = 1 % we will let f = 2 Hz A = 1.0; f = 2.0; y = sin(2.0*pi*f*t); % WAIT!!! % t is a long array!!! % That is OK because sin will evaluate the function at EVERY value of t % The result is an array y of equal length size(y) % we can plot this figure; plot(t,y) % can control the colors figure; plot(t,y,'k'); % we can add points and change the line figure; plot(t,y,'k:'); hold; plot(t,y,'r*'); % CLOSE close close all % remember the random numbers N = randn(1,1000); % we can make a histogram figure; hist(N); % SAVE AN LOAD THE WORKSPACE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % what directory am I in? pwd % how do I change it? cd 'C:/' % in functional form cd('C:/') % what is in that directory ls dir % save the workspace save myWorkspace % or as a function save('myWorkspace'); % save a two variables save partOfWorkspace t y N % clear clear all % load the workspace load partOfWorkspace % make a plot figure; hist(N) % CONTROL %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % IF-ELSE-THEN a = 6; if a/2 == round(a/2) disp('a is even'); else disp('a is odd'); end % FOR LOOPS for i = 1:10000 b(i) = 2*i; end % note that this is defining and creating the array b as it goes % we could have defined b first and set it to zero % LETS TIME THIS... clear b; tic; for i = 1:10000 b(i) = 2*i; end toc; % OK, now the other way clear b; tic; b = zeros(1,10000); for i = 1:10000 b(i) = 2*i; end toc; % This was MUCH FASTER! % But we could have defined b from the start by: clear b; tic; b = [2:2:20000]; toc; % CRAZY FAST!!! % Matrix Laboratory! % LESSON: Vectorize your Loops % while loops keepgoing = 1; while keepgoing keepgoing = keepgoing + 1; if keepgoing == 10 keepgoing = 0; end disp(keepgoing) end % WORKBOOK or NOTEBOOK or WHATEVER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Use the Editor to keep notes of your EXPERIMENTS % Save your command history % Save your notes and ideas % Use the editor to work your way through a complex function % Commands can be cut-and-pasted from the Editor into the Command Window % Commands can be cut-and-pasted from the Command History to the Editor % Save them in an appropriate dictionary % Name them appropriately % YYYYMMDD-NN-Name % The above format keeps it in chronological order and allows searching % M-FILES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % M-Files are how Matlab handles FUNCTIONS or SUBROUTINES % FORMAT OF AN M-FILE % Commented Description - USED BY HELP! % here is a function to add two numbers function result = add(a,b) result = a + b; return % Demonstrate SMART INDENT % Demonstrate COMMENT % save M-File as add.m % NOTE THAT THE NAME 'add' MATCHES THE FUNCTION NAME % THE PATH %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Matlab looks for unrecognized M-file names by searching the PATH % Demonstration the Path % save the M-file 'add.m' in one folder % modify 'add.m' to add pi to a and b: result = a + b + pi; % save the M-file in a separate folder % set up the path for the first folder % show how the first version of 'add.m' runs % add the second folder % show how the second version of 'add.m' runs % show how the first version runs, if it is higher in the path sequence % YOUR WORK %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Your work should be of professional quality % Leave your chicken scratchings in your Workbook % 1. Use a Separate Folder for Each Project % 2. Common M-Files can be duplicated and put in a Common Folder % 3. Document ALL Code. HELP Functionality Should Be Present. % 4. Abstract Out Stand-Alone Functions. % 5. Make a habit of Saving your Workspace and Plots during Experiments % 6. Check Your PATH % IMPROVING PERFORMANCE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % search for 'Techniques for Improving Performance' doc % profile function % first look at this function magic(5) % now where are its bottlenecks? profile on plot(magic(35)) profile viewer p = profile('info'); % You can watch the function call other functions profile on -history plot(magic(4)); p = profile('info'); for n = 1:size(p.FunctionHistory,2) if p.FunctionHistory(1,n)==0 str = 'entering function: '; else str = 'exiting function: '; end disp([str p.FunctionTable(p.FunctionHistory(2,n)).FunctionName]) end