Introduction to MATLAB Programming opencadd.br

34 Slides288.00 KB

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 Comments start start with with "%" "%" character character pause pause %% Suspend Suspend execution execution -- hit hit any any key key to to continue. continue. keyboard keyboard %% Pause Pause && return return control control to to command command line. line. %% Type Type "return" "return" to to continue. continue. break break %% Terminate Terminate execution execution of of current current loop/file. loop/file. return return %% Exit Exit current current function function %% Return Return to to invoking invoking function/command function/command line. 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 Short-circuited in MATLAB - once a condition is true, the sequence terminates. if if II JJ A(I,J) A(I,J) 2; 2; elseif elseif abs(I-J) abs(I-J) 11 A(I,J) A(I,J) -1; -1; else else A(I,J) A(I,J) 0; 0; end 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 switch input num input num case case -1 -1 input str input str 'minus 'minus one'; one'; case case 00 input str input str 'zero'; 'zero'; case case 11 input str input str 'plus 'plus one'; one'; case case {-10,10} {-10,10} input str input str ' /' /- ten'; ten'; otherwise otherwise input str input str 'other 'other value'; value'; end 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; N 10; for for II 1:N 1:N for for JJ 1:N 1:N A(I,J) A(I,J) 1/(I J-1); 1/(I J-1); end end 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; I 1; N 10; N 10; while while I N I N J 1; J 1; while while J N J N A(I,J) 1/(I J-1); A(I,J) 1/(I J-1); J J 1; J J 1; end end I I 1; I I 1; end end »while examp Copyright 1984 - 1998 by The MathWorks, Inc.

Introduction to MATLAB Programming - 11 Recall: Array Operations Using Array Operations: Density Density Mass(I,J)/(Length.*Width.*Height); Mass(I,J)/(Length.*Width.*Height); Using Loops: [rows, cols] [rows, cols] size(M); size(M); for for II 1:rows 1:rows for for JJ 1:cols 1:cols Density(I,J) Density(I,J) M(I,J)/(L(I,J)*W(I,J)*H(I,J)); M(I,J)/(L(I,J)*W(I,J)*H(I,J)); end end 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 This file file creates creates the the first first NN magic magic matrices. matrices. %% Each Each matrix matrix is is saved saved as as aa variable: variable: "magic#". "magic#". NN 10; 10; for for II 1:N 1:N eval(['magic', eval(['magic', num2str(I), num2str(I), '' magic(I)']); magic(I)']); end 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, [parts, shifts] size(data); shifts] size(data); for for I 1:shifts I 1:shifts DATA DATA data(:,I); data(:,I); MEAN mean(DATA); MEAN mean(DATA); deviation deviation STDEV STDEV std(DATA); std(DATA); %% Calculating Calculating mean mean && Std. Std. figure(I); %% Creating figure(I); clf; clf; hold hold on on Creating plots plots plot(1:parts, DATA, 'b'); plot(1:parts, DATA, 'b'); plot([0 plot([0 parts], parts], [0 [0 0], 0], 'k:',. 'k:',. [0 [0 parts], parts], [1 [1 1]*MEAN, 1]*MEAN, 'r-.',. 'r-.',. [0 parts], [1 1]*(MEAN-STDEV), [0 parts], [1 1]*(MEAN-STDEV), 'r:',. 'r:',. [0 parts], [1 1]*(MEAN STDEV), 'r:',. [0 parts], [1 1]*(MEAN STDEV), 'r:',. ); ); %% .etc. .etc. %% Writing Writing variables variables to to workspace workspace eval(['data', eval(['data', num2str(I), num2str(I), ' data(:,I);']); ' data(:,I);']); eval(['mean', num2str(I), ' means(I);']); eval(['mean', num2str(I), ' means(I);']); eval(['stdev', eval(['stdev', num2str(I), num2str(I), ' stdev(I);']); ' stdev(I);']); end 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 function yy mean(x) mean(x) %% MEAN MEAN Average Average or or mean mean value. value. Online Help %% For For vectors, vectors, MEAN(x) MEAN(x) returns returns the the mean mean value. value. %% For For matrices, matrices, MEAN(x) MEAN(x) is is aa row row vector vector %% containing containing the the mean mean value value of of each each column. column. [m,n] [m,n] size(x); size(x); MATLAB Code if if mm 11 mm n; n; end end yy sum(x)/m; 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 function rr ourrank(X,tol) ourrank(X,tol) %% OURRANK OURRANK Rank Rank of of aa matrix matrix ss svd(X); svd(X); if if (nargin (nargin 1) 1) tol tol max(size(X))*s(1)*eps; max(size(X))*s(1)*eps; end end rr sum(s sum(s tol); tol); Multiple Input Arguments ( , ) Multiple Output Arguments [ , ] function function [mean,stdev] [mean,stdev] ourstat(x) ourstat(x) %% OURSTAT OURSTAT Mean Mean && std. std. deviation deviation [m,n] [m,n] size(x); size(x); if if mm 11 mm n; n; end end mean mean sum(x)/m; sum(x)/m; stdev stdev sqrt(sum(x. 2)/m sqrt(sum(x. 2)/m –– mean. 2); 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 Modified Script Script file file %% %% This This solution solution sets sets the the figure#, figure#, overwrites overwrites the the title, title, && %% writes writes the the workspace workspace variables variables outside outside the the function. function. shifts size(data,2); shifts size(data,2); for for I 1:shifts I 1:shifts DATA DATA data(:,I); data(:,I); figure(I) figure(I) %% Function Function Call Call [MEAN, [MEAN, STDEV] STDEV] func plot(DATA); func plot(DATA); %% Writing Writing variables variables to to workspace workspace eval(['data', num2str(I), ' DATA;']); eval(['data', num2str(I), ' DATA;']); eval(['mean', eval(['mean', num2str(I), num2str(I), ' MEAN;']); ' MEAN;']); eval(['stdev', eval(['stdev', num2str(I), num2str(I), ' STDEV;']); ' STDEV;']); end 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 function [MEAN, [MEAN, STDEV] STDEV] func plot(data) func plot(data) %% FUNC PLOT FUNC PLOT Calculates Calculates mean mean && std. std. deviation deviation && plots plots data data DATA data(:); DATA data(:); parts parts length(DATA); length(DATA); MEAN MEAN mean(DATA); mean(DATA); STDEV STDEV std(DATA); std(DATA); %% Calculating Calculating mean mean && Std. Std. deviation deviation clf; %% Creating clf; hold hold on on Creating plots plots plot(1:parts, DATA, 'b'); plot(1:parts, DATA, 'b'); plot([0 plot([0 parts], parts], [0 [0 0], 0], 'k:',. 'k:',. [0 [0 parts], parts], [1 [1 1]*MEAN, 1]*MEAN, 'r-.',. 'r-.',. [0 parts], [1 1]*(MEAN-STDEV), [0 parts], [1 1]*(MEAN-STDEV), 'r:',. 'r:',. [0 parts], [1 1]*(MEAN STDEV), 'r:',. [0 parts], [1 1]*(MEAN STDEV), 'r:',. ); ); %% .etc. .etc. xlabel('Part xlabel('Part Number'); Number'); ylabel('Deviation ylabel('Deviation from from Spec. Spec. (mm)'); (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 Primary Function function function [totalsum,average] [totalsum,average] subfunc subfunc (input vector) (input vector) %% SUBFUNC SUBFUNC Calculates Calculates cumulative cumulative total total && average average totalsum totalsum sum(input vector); sum(input vector); average average ourmean(input vector); ourmean(input vector); %Call %Call to to subfunction subfunction function function yy ourmean(x) ourmean(x) %% (OURMEAN) (OURMEAN) Calculates Calculates average average SubFunction [m,n] [m,n] size(x); size(x); if if mm 11 mm n; n; end end yy sum(x)/m; 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 M-file »» cos 'This cos 'This string.'; string.'; »» cos(8) cos(8) ans ans rr »» clear clear cos cos »» cos(8) cos(8) ans ans -0.1455 -0.1455 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.

Back to top button