matlab second seminar. previous lesson last lesson we learnt how to: interact with matlab in the...

24
MATLAB MATLAB Second Seminar Second Seminar

Upload: oswald-gray

Post on 11-Jan-2016

229 views

Category:

Documents


9 download

TRANSCRIPT

Page 1: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

MATLABMATLABSecond SeminarSecond Seminar

Page 2: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Previous lessonPrevious lesson

Last lesson We learnt how to:• Interact with MATLAB in the MATLAB command

window by typing commands at the command prompt.• Define and use variables.• Plot graphs

It would be nice if you didn't have to manually type these commands at the command prompt whenever you want to use

them.

Page 3: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

• Write a script that asks for a temperature (in degrees Fahrenheit)

• computes the equivalent temperature in degrees Celcius.

• The script should keep running until no number is provided to convert.

• use isempty

ProblemProblem

Page 4: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

SolutionSolution

while 1 % use of an infinite loop

TinF = input('Temperature in F: '); % get input

if isempty(TinF) % how to get out

break

end

TinC = 5*(TinF - 32)/9; % conversion

disp(' ')

disp([' ==> Temperature in C = ',num2str(TinC)])

disp(' ')

end

while 1 % use of an infinite loop

TinF = input('Temperature in F: '); % get input

if isempty(TinF) % how to get out

break

end

TinC = 5*(TinF - 32)/9; % conversion

disp(' ')

disp([' ==> Temperature in C = ',num2str(TinC)])

disp(' ')

end

Page 5: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

FunctionsFunctions

• Functions describe subprograms–Take inputs, generate outputs–Have local variables (invisible in global workspace)

• Core MATLAB (Built-in) Functions–sin, abs, exp, ...Can’t be displayed on screen

• MATLAB-supplied M-file Functions–mean, linspace, …Ca be displayed on screen

• User-created M-file Functions

Page 6: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Core MATLAB (Built-in) Functions

• Elementary built-in functions • >> help elfun % a list of these functions   

• Special Math functions • >> help specfun 

• Special functions - toolboxes • Each toolbox has a list of special functions that you can use

sin         % Sine. exp         % Exponential. abs         % Absolute value. round       % Round towards nearest integer.

sin         % Sine. exp         % Exponential. abs         % Absolute value. round       % Round towards nearest integer.

lcm         % Least common multiple.cart2sph    % Transform Cartesian to spherical % coordinates.

lcm         % Least common multiple.cart2sph    % Transform Cartesian to spherical % coordinates.

Page 7: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

function y = mean(x)

% MEAN Average or mean value.

% 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);

if m == 1

m = n;

end

y = sum(x)/m;

function y = mean(x)

% MEAN Average or mean value.

% 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);

if m == 1

m = n;

end

y = sum(x)/m;

Structure of a Function M-fileStructure of a Function M-file

Keyword: function Function Name (same as file name .m)

Output Argument(s) Input Argument(s)

Online Help

MATLABCode

»output_value = mean(input_value) Command Line Syntax

Page 8: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Multiple Input & Output ArgumentsMultiple Input & Output Arguments

function r = ourrank(X,tol)% OURRANK Rank of a matrixs = svd(X);if (nargin == 1)

tol = max(size(X))*s(1)*eps;

endr = sum(s > tol);

function r = ourrank(X,tol)% OURRANK Rank of a matrixs = svd(X);if (nargin == 1)

tol = max(size(X))*s(1)*eps;

endr = 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);

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);

Multiple Input Arguments ( , )

Multiple Output Arguments [ , ]

» RANK = ourrank(rand(5),0.1);» [MEAN,STDEV] = ourstat(1:99);

Page 9: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

nargin, nargout, nargchknargin, nargout, nargchk

• nargin – number of input arguments- Many of Matlab functions can be run with different number of input variables.

• nargout – number of output arguments- efficiency

• nargchk – check if number of input arguments is between some ‘low’ and ‘high’ values

Page 10: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Workspaces in MATLABWorkspaces in MATLAB

• MATLAB (or Base) Workspace:

– For command line and script file variables.

• Function Workspaces:

– Each function has its own workspace for local variables.

– Name of Input/output variables can be either equal or different then the variable name in the calling workspace.

– Communicate to Function Workspace via inputs & outputs.

• Global Workspace:

Global variables can be shared by multiple workspaces.

(Must be initialized in all relevant workspaces.)

Initialize global variables in all relevant workspaces:»global variable_name

Initialize global variables in the “source” workspace before referring to them from other workspaces.

Page 11: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Tips for using Global VariablesTips for using Global Variables

• DON’T USE THEM

• If you absolutely must use them:– Avoid name conflicts

>>whos global %shows the contents of the global workspace

>>clear global %erases the variable from both local and global workspaces.

>>isglobal()

Page 12: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

MATLAB Calling PriorityMATLAB Calling Priority

High

variable

built-in function

subfunction

private function

MEX-file

P-file

M-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

Page 13: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Visual DebuggingVisual Debugging

Set BreakpointClear BreaksStep InSingle StepContinueQuit Debugging

Select Workspace

Set Auto-Breakpoints

Page 14: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Example: Visual Debugging (2)Example: Visual Debugging (2)

• Editor/Debugger opens the relevant file and identifies the line where the error occurred.

CurrentLocation Current

Workspace (Function)

Page 15: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Example: Visual Debugging (3)Example: Visual Debugging (3)

Error messageError message

Access to Function’s Workspace

Access to Function’s WorkspaceDebug

ModeDebug Mode

Page 16: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Some Useful MATLAB commandsSome Useful MATLAB commands

• what List all m-files in current directory

• dir List all files in current directory

• ls Same as dir

• type test Display test.m in command window

• delete test Delete test.m

• cd a: Change directory to a:

• chdir a: Same as cd

• pwd Show current directory

• which test Display current directory path to

test.m

• why In case you ever needed a reason

Page 17: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

• Write a function that asks for a temperature (in degrees Fahrenheit)

• computes the equivalent temperature in degrees Celcius.

• The function should give an error massage in case no number is provided to convert.

• use nargin.

ProblemProblem

Page 18: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

SolutionSolution

function TinC=temp2(TinF)TinF = input('Temperature in F: '); % get input

if nargin==0 % if there is no input

disp('no temparture was entered');

TinC=nan;

else

TinC = 5*(TinF - 32)/9; % conversion

disp(' ')

disp([' ==> Temperature in C = ',num2str(TinC)])

disp(' ')

end

function TinC=temp2(TinF)TinF = input('Temperature in F: '); % get input

if nargin==0 % if there is no input

disp('no temparture was entered');

TinC=nan;

else

TinC = 5*(TinF - 32)/9; % conversion

disp(' ')

disp([' ==> Temperature in C = ',num2str(TinC)])

disp(' ')

end

Page 19: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

MATLAB InputMATLAB Input

To read files in• if the file is an ascii table, use “load”

• if the file is ascii but not a table, file I/O needs “fopen” and “fclose”

• Reading in data from file using fopen depends on type of data (binary or text)

• Default data type is “binary”

Page 20: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

What Is GUIDE?What Is GUIDE?

• Graphical User Interface Design Environment

• provides a set of tools for creating graphical user interfaces (GUIs).

• GUIDE automatically generates an M-file that controls how the GUI operates.

• Starting GUIDE:

>> guide

OR:

Push buttons

Static text

Pop-up menu

axes

Page 21: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

GUIDE Tools - The Layout EditorGUIDE Tools - The Layout Editor

• In the Quick Start dialog, select the Blank GUI (Default) template

• Display names of components: File preferences Show names in component palette

• Lay out your GUI by dragging components

(panels, push buttons, pop-up menus, or axes)

from the component palette, into the layout area

Drag to resize

Component panel

Layout area

Page 22: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Using the Property InspectorUsing the Property Inspector

• Labeling the Buttons

• Select Property Inspector from the View menu.

• Select button by clicking it.

• Fill the name in the String field.

Activate GUI

Property

Inspector

Page 23: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Programming a GUIProgramming a GUI

• Callbacks are functions that execute in response to some action by the user.

• A typical action is clicking a push button.

• You program the GUI by coding one or more callbacks for each of its components.

• A GUI's callbacks are found in an M-file that GUIDE generates automatically.

• Callback template for a push button:

Page 24: MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command

Handles structureHandles structure

• Save the objects handles: handles.objectname

• Save global data – can be used outside the function.

• Example: popup menu:

• Value – user choice of the popup menu