Introduction to MATLAB Programming www.opencadd.com.br Introduction to MATLAB Programming - 2 Section Outline • • Script Files • • Flow Control & Array Operations EVAL Command Functions • • • • Structural Syntax Variables & Workspaces Subfunctions and Private Functions Visual Debugging Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 3 The MATLAB Path • MATLAB Path: • • • List of directories searched by MATLAB. (Includes \toolbox directories) Path Cache: • • • List of \toolbox files & locations. Created at startup to increase speed. Only updated when PATH command is called. Working with the Path: • • Path Browser (PATHTOOL) PATH, ADDPATH, RMPATH Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 4 MATLAB Editor/Debugger »edit <filename> Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 5 Script M-files • • Standard ASCII text files Contain a series of MATLAB expressions (Typed as you would at the command line) • Commands parsed & executed in order % Comments start with "%" character pause % Suspend execution - hit any key to continue. keyboard % Pause & return control to command line. % Type "return" to continue. break % Terminate execution of current loop/file. return % Exit current function % Return to invoking function/command line. Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 6 Flow Control Constructs • • Logic Control: • • IF / ELSEIF / ELSE SWITCH / CASE / OTHERWISE Iterative Loops: • • FOR WHILE Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 7 The if, elseif and else statements • • Works on Conditional statements if I == J Short-circuited in MATLAB - once a condition is true, the sequence terminates. elseif abs(I-J) == 1 A(I,J) = 2; A(I,J) = -1; else A(I,J) = 0; end »if_examp Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 8 Switch, Case, and Otherwise • • More efficient than elseif statements Only the first matching case is executed switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end »switch_examp Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 9 The for loop • • • Similar to other programming languages Repeats loop a set number of times (based on index) Can be nested N=10; for I = 1:N for J = 1:N A(I,J) = 1/(I+J-1); end end »for_examp Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 10 The while loop • Similar to other programming languages • Repeats loop until logical condition returns FALSE. • Can be nested. I=1; N=10; while I<=N J=1; while J<=N A(I,J)=1/(I+J-1); J=J+1; end I=I+1; end »while_examp Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 11 Recall: Array Operations • Using Array Operations: Density = Mass(I,J)/(Length.*Width.*Height); • Using Loops: [rows, cols] = size(M); for I = 1:rows for J = 1:cols Density(I,J) = M(I,J)/(L(I,J)*W(I,J)*H(I,J)); end end »array_vs_loops Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 12 EVAL Command • Evaluates the MATLAB expression specified by the input string. • Very useful for inserting indices into strings. % This file creates the first N magic matrices. % Each matrix is saved as a variable: "magic#". N = 10; for I = 1:N eval(['magic', num2str(I), ' = magic(I)']); end »eval_examp Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 13 Exercise: Script M-files Write a script file to monitor process variation: • Load data: >> data = load('script_data.txt'); (M-by-N process data matrix - M parts per shift, N shifts) • For each shift: • • Calculate the mean & standard deviation. Save the data, mean & SD to the workspace. (Use a separate variable for each shift: data1, data2, ...) • • • Plot the data in a new figure window. Plot lines showing the mean and up to +/- 3 STD. Annotate the figure appropriately. Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 14 Results: Script M-files Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 15 Solution: Script M-files [parts, shifts]=size(data); for I=1:shifts DATA = data(:,I); MEAN = mean(DATA); STDEV = std(DATA); % Calculating mean & Std. deviation figure(I); clf; hold on % Creating plots plot(1:parts, DATA, 'b'); plot([0 parts], [0 0], 'k:',... [0 parts], [1 1]*MEAN, 'r-.',... [0 parts], [1 1]*(MEAN-STDEV), 'r:',... [0 parts], [1 1]*(MEAN+STDEV), 'r:',... ); % .....etc. % Writing variables to workspace eval(['data', num2str(I), '=data(:,I);']); eval(['mean', num2str(I), '=means(I);']); eval(['stdev', num2str(I), '=stdev(I);']); end »script_soln (uses: script_data.txt) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 16 Functions • • • Core MATLAB (Built-in) Functions • sin, abs, exp, ... MATLAB-supplied M-file Functions • mean, stat, … User-created M-file Functions • • ????? Differences between Script & Function M-files: • • Structural Syntax Function Workspaces, Inputs & Outputs Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 17 Structure of a Function M-file Keyword: function Function Name (same as file name .m) Output Argument(s) Input Argument(s) function y = mean(x) % MEAN Average or mean value. Online Help % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); MATLAB Code if m == 1 m = n; end y = sum(x)/m; »output_value = mean(input_value) Command Line Syntax Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 18 Multiple Input & Output Arguments function r = ourrank(X,tol) % OURRANK Rank of a matrix Multiple Input Arguments ( , ) s = svd(X); if (nargin == 1) tol = max(size(X))*s(1)*eps; Multiple Output Arguments [ , ] end r = sum(s > tol); function [mean,stdev] = ourstat(x) % OURSTAT Mean & std. deviation [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2); »RANK = ourrank(rand(5),0.1); »[MEAN,STDEV] = ourstat(1:99); Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 19 Workspaces in MATLAB • MATLAB (or Base) Workspace: For command line and script file variables. • Function Workspaces: Each function has its own workspace for local variables. Communicate to Function Workspace via inputs & outputs. (Promotes structured coding & prevents name conflicts.) • Global Workspace: Global variables can be shared by multiple workspaces. (Must be initialized in all relevant workspaces.) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 20 Inter-Workspace Communication Function inputs and outputs Global variables (AVOID THESE) Initialize global variables in all relevant workspaces: »global variable_name MATLAB Workspace Function Workspace Global Workspace Initialize global variables in the “source” workspace before referring to them from other workspaces. Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 21 Tips for using Global Variables • DON’T USE THEM • If you absolutely must use them: • • • • Avoid name conflicts whos global clear global isglobal() Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 22 Exercise: Function M-files Let’s go back to the process monitoring exercise: • Start with your script file (or the given solution) >> edit script_soln • Create a function which replicates as much of the code inside the for loop as possible. (NOTE: It may not make sense to replace everything) • • Now modify your script file to call your function. Run your new script file and compare the results. Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 23 Results: Function M-files Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 24 Solution: Function M-files (1) % % % % Modified Script file ==================== This solution sets the figure#, overwrites the title, & writes the workspace variables outside the function. shifts=size(data,2); for I=1:shifts DATA = data(:,I); figure(I) % Function Call [MEAN, STDEV] = func_plot(DATA); % Writing variables to workspace eval(['data', num2str(I), '=DATA;']); eval(['mean', num2str(I), '=MEAN;']); eval(['stdev', num2str(I), '=STDEV;']); end »func_soln (uses: func_plot & script_data.txt) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 25 Solution: Function M-files (2) function [MEAN, STDEV] = func_plot(data) % FUNC_PLOT Calculates mean & std. deviation & plots data DATA = data(:); parts= length(DATA); MEAN = mean(DATA); STDEV = std(DATA); % Calculating mean & Std. deviation clf; hold on % Creating plots plot(1:parts, DATA, 'b'); plot([0 parts], [0 0], 'k:',... [0 parts], [1 1]*MEAN, 'r-.',... [0 parts], [1 1]*(MEAN-STDEV), 'r:',... [0 parts], [1 1]*(MEAN+STDEV), 'r:',... ); % .....etc. xlabel('Part Number'); ylabel('Deviation from Spec. (mm)'); »func_soln (uses: func_plot & script_data.txt) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 26 Subfunctions • Allows more than one function to be within the same M-file (modularize code) • M-file must have the name of the first (primary) function • Subfunctions can only be called from within the same M-file • Each subfunction has its own workspace Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 27 Example: Subfunctions function [totalsum,average] = subfunc (input_vector) Primary Function % SUBFUNC Calculates cumulative total & average totalsum = sum(input_vector); average = ourmean(input_vector); %Call to subfunction function y = ourmean(x) % (OURMEAN) Calculates average SubFunction [m,n] = size(x); if m == 1 m = n; end y = sum(x)/m; »[SUM, MEAN] = subfunc(rand(1,50)) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 28 Private Functions • • private directory Reside in a subdirectory named "private" Only accessible to functions in parent directory Only accessible to functions in parent directory. Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 29 MATLAB Calling Priority High variable built-in function subfunction private function MEX-file P-file » cos='This string.'; » cos(8) ans = r » clear cos » cos(8) ans = -0.1455 M-file Low Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 30 Visual Debugging Select Workspace Set AutoBreakpoints Set Breakpoint Clear Breaks Step In Single Step Continue Quit Debugging »[SUM, MEAN] = subfunc(rand(1,50)) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 31 Example: Visual Debugging • Set up your debugger to stop if an error occurs • Then run: »[SUM, MEAN] = subfunc_error(rand(1,50)) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 32 Example: Visual Debugging (2) • Current Location Editor/Debugger opens the relevant file and identifies the line where the error occurred. Current Workspace (Function) Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 33 Example: Visual Debugging (3) Error message Debug Mode Access to Function’s Workspace Copyright 1984 - 1998 by The MathWorks, Inc. Introduction to MATLAB Programming - 34 Section Summary • • Script Files • • Flow Control & Array Operations EVAL Command Functions • • • • Structural Syntax Variables & Workspaces Subfunctions and Private Functions Visual Debugging Copyright 1984 - 1998 by The MathWorks, Inc.