matlab editor - bgutools/matlab/matlab_seminar2.pdf · advanced programming techniques in matlab 2...

25
2 - 1 Advanced Programming Techniques in MATLAB © 2002 The MathWorks, Inc >> edit % Opens new file OR brings editor into focus >> edit welcomefile % Opens file named welcomefile.m MATLAB Editor

Upload: lamdien

Post on 07-Jun-2018

233 views

Category:

Documents


0 download

TRANSCRIPT

2 - 1Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

>> edit % Opens new file OR brings editor into focus>> edit welcomefile % Opens file named welcomefile.m

MATLAB Editor

2 - 2Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

% Comments start with "%" character

pause % Suspend execution. Press any key to continue.

keyboard % Pause & return control to command line.% Type "return" to continue.

break % Terminate execution of current loop/file.

return % Return to invoking function/command line.

input % Prompt for user input.

% Comments start with "%" character

pause % Suspend execution. Press any key to continue.

keyboard % Pause & return control to command line.% Type "return" to continue.

break % Terminate execution of current loop/file.

return % Return to invoking function/command line.

input % Prompt for user input.

Script M-Files• Are standard ASCII text files• Contain a series of MATLAB expressions(Typed as you would at the command line)

• Commands are parsed and executed in order

2 - 3Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Example: Script M-Filesdisp('I''m thinking of a number from 1 to 10.');secretNum = fix(10*rand + 1); % Will be integer.keyboardguessed = false;while ~guessed

thisGuess = input('Guess, or type -1 to give up: ');if thisGuess == secretNum

guessed = true;return

elseif thisGuess == -1break

elsedisp('Wrong! Try again.');

endend

>> numguess

2 - 4Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Functions• Core MATLAB (built-in) functions

• sin, abs, exp, etc.• MATLAB supplied M-file functions

• mean, std, etc.• User-created M-file functions

• Wherever your imagination takes you...

• Differences between script and function M-files• Structural syntax• Function workspaces, inputs, and outputs

2 - 5Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

function y = mymean(x)

%MYMEAN Average or mean value.

% For vectors, MYMEAN(x) returns the mean value.

% For matrices, MYMEAN(x) is a row vector

% containing the mean value of each column.

[m,n] = size(x);

if m == 1

m = n;

end

y = sum(x)/m;

function y = mymean(x)

%MYMEAN Average or mean value.

% For vectors, MYMEAN(x) returns the mean value.

% For matrices, MYMEAN(x) is a row vector

% containing the mean value of each column.

[m,n] = size(x);

if m == 1

m = n;

end

y = sum(x)/m;

Structure of a Function M-fileKeyword: function Function Name (same as file name .m)

Output Argument(s) Input Argument(s)

Online Help

MATLABCode

>> output_value = mymean(input_val)

Command Line Syntax

2 - 6Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Subfunctions• Using subfunctions allows more than one

function to be within the same M-file (modularize code).

• M-files containing subfunctions 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.

The file stats.m is an example of a function M-file with a subfunction.

>> edit stats

2 - 7Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Private Functions• Reside in a subdirectory named private• Only accessible to functions in parent directory

Only accessible to functions inparent directory.private

directory

>> mytest2

2 - 8Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

MATLAB Calling Priority

HighVariableBuilt-in functionSubfunctionPrivate functionFiles

Mex-fileP-fileM-file

Low

>> cos='This string.';

>> cos(8)

ans =

r

>> clear cos

>> cos(8)

ans =

-0.1455

>> cos='This string.';

>> cos(8)

ans =

r

>> clear cos

>> cos(8)

ans =

-0.1455

2 - 9Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Flow Control Constructs• Logic control:

• if / elseif / else• switch / case / otherwise

• Iterative loops:• for• while

2 - 10Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

if I == J

A(I,J) = 2;

elseif abs(I-J) == 1

A(I,J) = -1;

else

A(I,J) = 0;

end

if I == J

A(I,J) = 2;

elseif abs(I-J) == 1

A(I,J) = -1;

else

A(I,J) = 0;

end

Logical Control ProgrammingConstructs

switch algorithm

case 'ode23'

str = '2nd/3rd order';

case {'ode15s', 'ode23s'}

str = 'stiff system';

otherwise

str = 'other algorithm';

end

switch algorithm

case 'ode23'

str = '2nd/3rd order';

case {'ode15s', 'ode23s'}

str = 'stiff system';

otherwise

str = 'other algorithm';

end

>> if_examp>> switch_examp

• Work on conditional statements• Short-circuited in MATLAB - once a condition is true, or case

matched, the sequence terminates.• switch-case statements are more efficient than if-elseif

statements when working with strings.

2 - 11Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Iterative Loops

I = 1; N = 10;

while I <= NJ = 1;while J <= N

A(I,J) = 1/(I+J-1);J = J+1;

endI = I+1;

end

I = 1; N = 10;

while I <= NJ = 1;while J <= N

A(I,J) = 1/(I+J-1);J = J+1;

endI = I+1;

end

>> for_examp>> while_examp

• Similar to other programming languages• for -- Repeats loop a set number of times (based on index)• while -- Repeats loop until logical condition returns FALSE• Can be nested

N = 10;

for I = 1:N

for J = 1:N

A(I,J) = 1/(I+J-1);

end

end

N = 10;

for I = 1:N

for J = 1:N

A(I,J) = 1/(I+J-1);

end

end

2 - 12Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.Options from the Breakpoints menu.

MATLAB Debugger

2 - 13Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Example: Visual Debugging• Set up your debugger to stop if an error occurs

Then run: >> status = bank_info(100,0)

2 - 14Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Example: Visual Debugging (continued)

2 - 15Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

The MathWorks Inc.Natick, MA USA

GUIDEGraphical User Interface Design Environment

2 - 16Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Section Outline• Hands-on GUIDE Example• Writing Callbacks• Switchyard Programming

2 - 17Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

GUIDE Example (Final Product)

Static Text Box

Checkbox

Pushbuttons

Axes

Slider

UI Menu

Line Plot

2 - 18Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

• Open GUIDE >> guide• Collect UI Controls

2 - 19Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

GUIDE Tools

Push Button

Axes

Checkbox

Static Text Box

Slider Alignment Tool

Menu Editor

Property InspectorObject Browser

Activate Figure

GUIDE Toolbar

Component Palette

2 - 20Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Using the Property Inspector

>> gui_example

2 - 21Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Writing CallbacksWhat is a callback?• A sequence of commands that are executed when a graphics

object is activated.• Stored as a text string and is a property of a graphics object.

(e.g. CreateFcn, ButtonDownFcn, Callback, DeleteFcn)

Components of a callback:1. get handles of the objects initiating action

(objects providing event / information / values)2. get handles of the objects being affected

(objects whose properties are to be changed) 3. get necessary information / values4. set relevant object properties to effect action

2 - 22Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Callbacks (Example)

callback = ['pt = get(gca,''CurrentPoint'');'...

'xbox = findobj(''Tag'',''xbox'');' ...

'ybox = findobj(''Tag'',''ybox'');' ...

'set(xbox,''String'',num2str(pt(1,1)));'

callback = ['pt = get(gca,''CurrentPoint'');'...

'xbox = findobj(''Tag'',''xbox'');' ...

'ybox = findobj(''Tag'',''ybox'');' ...

'set(xbox,''String'',num2str(pt(1,1)));'

>> gui_example2

2 - 23Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Using Callback Editor (Continued)

2 - 24Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Using the Alignment Tool

1 Open Alignment Tool2 Select objects3 Select Align. Option(s)4 Apply/Revert Changes

2

4

3

4

2 - 25Advanced Programming Techniques in MATLAB

© 2002 The MathWorks, Inc.

Using Menu Editor

1 Open Menu Editor2 Add New Menu OR

New Menu Item3 Enter Label, Tag and

Callback Commands4 Apply Changes

Main MenuLabel = 'Load Data File'

Main MenuLabel = 'Load Data File'

Menu ItemLabel = 'MAT-File'

Callback:temp = cd;cd c:\class\matlab\examples;[filename, pathname] = uigetfile('*.mat'); load([pathname filename]);cd(temp);

Menu ItemLabel = 'MAT-File'

Callback:temp = cd;cd c:\class\matlab\examples;[filename, pathname] = uigetfile('*.mat'); load([pathname filename]);cd(temp);

3

2

2