Engineering H192 - Computer Programming

MATLAB: Script and Function Files
Lecture 19

Winter Quarter

The Ohio State Univ...
Engineering H192 - Computer Programming

MATLAB Script Files
• A MATLAB script file (Called an M-file) is a text
(plain AS...
Engineering H192 - Computer Programming

MATLAB Script Files
% This is a MATLAB script file.
% It has been saved as “g13.m...
Engineering H192 - Computer Programming

MATLAB Script Files
• The preceding file is executed by issuing a
MATLAB command:...
Engineering H192 - Computer Programming

MATLAB Script Files
• When the file is not in the current working
directory, a cd...
Engineering H192 - Computer Programming

MATLAB Demo
%MATLAB Example use of ginput
clear, clf, hold off
axis ([0, 10, 0, 1...
Engineering H192 - Computer Programming

MATLAB Function Files
• A MATLAB function file (called an M-file) is a text
(plai...
Engineering H192 - Computer Programming

MATLAB Function Files
• When the function is called in MATLAB, the file is
access...
Engineering H192 - Computer Programming

MATLAB Function Files
• The syntax for a MATLAB function definition is:
function ...
Engineering H192 - Computer Programming

MATLAB Function Files
• It is OK to use the same variable names in the
returned v...
Engineering H192 - Computer Programming

Example of a MATLAB Function File
function [ a , b ] = swap ( a , b )
% The funct...
Engineering H192 - Computer Programming

Example of a MATLAB Function File
• To use the function a MATLAB program could
as...
Engineering H192 - Computer Programming

MATLAB Function Files
• Referring to the function, the comments immediately
follo...
Engineering H192 - Computer Programming

MATLAB Function Files
• The MATLAB function must be in the current
working direct...
Engineering H192 - Computer Programming

MATLAB Function Files
• When the function file is not in the current
working dire...
Engineering H192 - Computer Programming

MATLAB Function Files
• Unlike C, a MATLAB variable does not have to be
declared ...
Engineering H192 - Computer Programming

MATLAB Function Files
function [n] = factorial (k)
% The function [n] = factorial...
Upcoming SlideShare
Loading in …5
×

Lecture 19 matlab_script&function_files06

285 views
201 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
285
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Instructor notes:
    This set of slides covers script files and function files. These are Matlab’s programming options.
  • Instructor notes:
    There are two types of M-files…script files and function files. We start out with script files. Script files are called M-files because the extension on the file is “.m”. Script files are a collection of Matlab commands that when executed are the same as if the commands had been entered from the keyboard. Variables that are used in script files are equivalent to global variables. A variable that originates in a script file is immediately known in the command window. Variables that originated in the command window are known in the script file. This is one are in which script and function files differ. Function files, like C/C++ functions use local variables which must be passed in and out of the function.
  • Instructor notes:
    This example demonstrates several key things about Matlab script files. We’ve got the script file d13.m. In order to invoke it, Matlab’s current working directory must be the same directory as where d13.m is stored, or the entire pathname to the script file must be entered at the command prompt. The load d13.dat command will open the file, d13.dat. Because the entire pathname to d13.dat is not specified, the current working directory must contain d13.dat. The load will open the file and read the entire file into Matlab creating an array called d13 without the “.dat” extension. Note the semicolon at the end of the line. This will prevent the contents of the array from being echoed to the command window.
    The second line creates a vector called voltage by reading in all of the rows in column 4 from the d13 matrix. Again, note the semicolon at the end of the line.
    The third line creates a time vector by multiplying 0.005 times a vector that has elements 1 to the length of the voltage vector.
    The fourth line plots the time on the x-axis and the voltage on the y-axis opening a new window that contains the plot. Lines 5 and 6 add labels to the x-axis and y-axis respectively.
    Line seven places a title on the plot and line eight puts a grid on the plot.
  • Instructor notes:
    As the slide indicates, the d13.m script file is executed by entering d13 at the command prompt when the current working directory is set to the same directory in which d13.m exists. If Matlab cannot find the file, it will display an error message. Note, that you can add to Matlab’s default search path so that files do not have to be located in the current directory.
  • Instructor notes:
    If the script file that you want to execute is not in the current directory, then use the cd or chdir commands to move to the correct directory and then execute the script file. Note that there are icons at the top of the command window that allow you to use the mouse to navigate to the desired directory. This may be especially useful when you have some idea of the name or roughly where the file is located rather than knowing the exact name or path.
    In this example the file is stored on the a: drive at the root level.
  • Instructor notes:
    Here we have another script file example…again this one has a lot packed into it. This script file collects mouse clicks and depending on which button was clicked, places a corresponding symbol on the plot window where the mouse was located at the time of the click.
    Line 1 issues three commands: clear removes all variables from memory, clf clears the figure window, and hold off turns off the plot holding. When the hold is on and multiple plot commands are issued, the plots will be placed on the same figure. In this script the hold is just being initialized to off.
    Line 2 sets the axis limits for the x and y axes of the plot window. The axis limits can be set at any time, even after the plot is drawn. It’s equivalent to changing the size of a window looking at the plot and gives you the ability to zoom in or out on different regions if you want.
    Line 3 turns the hold on, this way any plotting commands that are issued will cause the plotting to be on the same plot.
    Line 4 plots a box on the graph and line 5 places the text string “Click inside box to quit” inside the box that was plotted, placing the beginning of the text at (1, 1.6).
    Line 5 starts a while loop that terminates with the second “end” statement. Since the condition of the while loop is “1”, it will operate forever, thus the only way to exit the while loop and terminate the program is to satisfy the final “if” condition within the loop which causes the “break” to execute and the while loop to terminate.
    Inside the while loop, on line 6, the Matlab function ginput () is used. It returns the x and y coordinates on the plot where the mouse button was clicked as well as which mouse button was clicked.
    Line 7 is an “if” statement that checks to see if mouse button 1 was clicked. If so, a red “+” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition.
    Line 8 is an “if” statement that checks to see if mouse button 2 was clicked. If so, a yellow “o” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition.
    Line 9 is an “if” statement that checks to see if mouse button 3 was clicked. If so, a green “*” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition.
    Line 10 is the final “if” condition. It checks to see if the (x,y) coordinates of mouse click fall within 1<x<2 and 2<y<3, which are the limits of the text box. If so, then the “break” is executed and the while loop ends. Line 11 is the “end” statement for line 10.
    Line 12 is the “end” statement for the while loop.
    Line 13 turns off the plot hold, thus allowing multiple plot windows to be opened again.
  • Instructor notes:
    Now that we’ve seen a script file, we’re going to move to function files. Function files in Matlab are very much like functions in C/C++. The key difference between function files and script files is that variables in function files are local. Any variables that are used within a function file need to be specified within the function or passed in as arguments in the argument list.
    You may want to point out the similarities between C/C++ functions and Matlab function files. One difference between the two is that while a C/C++ function can only “return” one value, Matlab functions can return as many as desired.
    The function file should have the same name as the function itself with the “.m” extension added to it.
    Unlike C/C++ functions which can only be called from within a program, Matlab function files can be called directly from the command window, from a script file, or from another function file.
  • Instructor notes:
    This first bullet points out the reason that variables inside of function files are local and not known to the command window is that executing a function file causes control to switch out of the Matlab workspace into the function file’s workspace.
    As the second and third bullet points indicate, the function file is not part of the Matlab workspace and therefore those variables that exist within the function file and their corresponding values are not known to the command window when control is returned from the function file. In order to transfer the values of desired variables back to the Matlab workspace, they must be passed back according to the function call syntax.
    What this boils down to is that variables that are being passed into the function need to appear in parentheses to the right of the function name during the function call and variables that are being passed back from the function to the Matlab workspace must appear in square brackets to the left of the equals sign in the function call and function definition.
  • Instructor notes:
    Most of the information on this slide has been previewed on the previous slide. Arguments that are going into the function appear within parentheses to the right of the function name when the function is called. This is how you would get variables from the Matlab workspace or another function file into the called function. Values that are being determined within the function and returned by the function appear in square brackets prior to the equal sign on the line on which the function is called. These values will be returned by the function back to the Matlab workspace of the workspace of another function if this function were called within another function.
    Just as in C/C++, it’s the value of the variables that’s being passed. Addresses are NOT passed between workspaces.
  • Instructor notes:
    Using the same variable names in the return list of a Matlab function call as in the argument list has the effect of assigning new values to those variables.. This is a key idea to get across.
  • Instructor notes:
    Here we have an example of a swap function that has the same variables in its argument list as it does in its returned values list. In this example a and b are passed into the function. Within the function, temp is assigned a’s value, a is assigned b’s value and temp, which is a’s original value, is assigned to b. So, by the end of swap, the values of a and b have been swapped. Then, the swapped a and b are returned. To actually have the swap of a and b have an effect in the workspace that called swap requires that in the call to the function, the same variables were used in the calling “return” list and the calling “argument” list.
    A side note here…the comments that occur immediately after the first line of the function definition will be displayed in the command window if the user types help function_name at the command prompt. So, in this example, if the user were, at the command prompt, to type help swap, then the six comment lines that appear in the function definition above, would be displayed in the command window.
  • Instructor notes:
    Here we see the result of calling the swap function. Note that the variables in the function call do not have to be a and b, since a and b are local to the function definition. What is necessary is that the variables in square brackets and in parentheses have the same name. When called with initial values of x=5 and y=6, swap switches the values of x and y in the calling workspace.
    Hopefully some carryover from C/C++ explanation of functions will help out here, but this is somewhat of an abstract point to get a grasp of and quite possibly should be gone over slowly on the board or with an example that demonstrates visually what is taking place. It is slightly different than what happens in the C/C++ examples of swap.
  • Instructor notes:
    As quickly mentioned on an earlier slide, when entering help function_name at the cojmmand prompt, the comment information that appears immediately beneath the first line of the function will be displayed as help information in the command window.
  • Instructor notes:
    A heads up for the students and a quick reminder…the Matlab function that is being called must exist in the current working directory, or be in a directory that is specified as part of Matlab’s default search path, otherwise Matlab will not be able to find the function and will return an error message.
    Not finding the function and finding the function but with a “signature” that does not match that of the function file, will result in an error message. That error message may be somewhat obtuse and may be along the lines of that given in the slide. So, it’s a good idea for both student and instructors to be on the lookout for error messages that do not appear to have anything to do with the problem at hand.
  • Instructor notes:
    A reminder to make sure you change your working directory to the directory in which the function file exists prior to executing the function file. Either the cd or chdir commands can be used, as well as the icons at the top of the command window.
  • Instructor notes:
    As the slide indicates, Matlab is more flexible in dealing with variables changing their data types on the fly than C would be. All that is required to change the data type of a variable, is to assign the variable to a new value.
    After having gotten used to the strict data typing of C this might take students some practice to get used to.
  • Instructor notes:
    Here we see the factorial function. It takes in argument “k” and returns value “n”. The main point here is that if k is less than zero, the factorial cannot be computed and n is assigned a string error message as its value. Otherwise, if the factorial can be computed, n is assigned the value of the factorial. So, on the fly Matlab is able to handle assigning to the same variable, different types of values.
  • Lecture 19 matlab_script&function_files06

    1. 1. Engineering H192 - Computer Programming MATLAB: Script and Function Files Lecture 19 Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    2. 2. Engineering H192 - Computer Programming MATLAB Script Files • A MATLAB script file (Called an M-file) is a text (plain ASCII) file that contains one or more MATLAB commands and, optionally, comments. • The file is saved with the extension ".m". • When the filename (without the extension) is issued as a command in MATLAB, the file is opened, read, and the commands are executed as if input from the keyboard. The result is similar to running a program in C. The following slide is the contents of an M-file. Note that there are no prompts (>>). Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    3. 3. Engineering H192 - Computer Programming MATLAB Script Files % This is a MATLAB script file. % It has been saved as “g13.m". load g13.dat; %Load data file voltage = g13( : , 4); %Extract volts vector time = .005*[1:length(voltage)]; %Create time vector plot (time, voltage) %Plot volts vs time xlabel ('Time in Seconds') % Label x axis ylabel ('Voltage') % Label y axis title ('Bike Strain Gage Voltage vs Time') grid %Put a grid on graph Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    4. 4. Engineering H192 - Computer Programming MATLAB Script Files • The preceding file is executed by issuing a MATLAB command: >> g13 • This single command causes MATLAB to look in the current directory, and if a file g13.m is found, open it and execute all of the commands. The result, in this case, is a plot of the data from g13.dat. • If MATLAB cannot find the file in the current working directory, an error message will appear. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    5. 5. Engineering H192 - Computer Programming MATLAB Script Files • When the file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a: % Make a: the current working directory >> g13 Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    6. 6. Engineering H192 - Computer Programming MATLAB Demo %MATLAB Example use of ginput clear, clf, hold off axis ([0, 10, 0, 10]) hold on plot ([1, 2, 2, 1, 1],[2, 2, 3, 3, 2]) text (1, 1.6, 'Click inside box to quit') while 1 [x, y, buttun] = ginput (1) if buttun == 1, plot (x, y, '+r'), end if buttun == 2, plot (x, y, 'oy'), end if buttun == 3, plot (x, y, '*g'), end if x > 1 & x < 2 & y > 2 & y < 3, break; end end hold off Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    7. 7. Engineering H192 - Computer Programming MATLAB Function Files • A MATLAB function file (called an M-file) is a text (plain ASCII) file that contains a MATLAB function and, optionally, comments. • The file is saved with the function name and the usual MATLAB script file extension, ".m". • A MATLAB function may be called from the command line or from any other M-file. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    8. 8. Engineering H192 - Computer Programming MATLAB Function Files • When the function is called in MATLAB, the file is accessed, the function is executed, and control is returned to the MATLAB workspace. • Since the function is not part of the MATLAB workspace, its variables and their values are not known after control is returned. • Any values to be returned must be specified in the function syntax. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    9. 9. Engineering H192 - Computer Programming MATLAB Function Files • The syntax for a MATLAB function definition is: function [val1, … , valn] = myfunc (arg1, … , argk) where val1 through valn are the specified returned values from the function and arg1 through argk are the values sent to the function. • Since variables are local in MATLAB (as they are in C), the function has its own memory locations for all of the variables and only the values (not their addresses) are passed between the MATLAB workspace and the function. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    10. 10. Engineering H192 - Computer Programming MATLAB Function Files • It is OK to use the same variable names in the returned value list as in the argument. The effect is to assign new values to those variables. As an example, the following slide shows a function that swaps two values. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    11. 11. Engineering H192 - Computer Programming Example of a MATLAB Function File function [ a , b ] = swap ( a , b ) % The function swap receives two values, swaps them, % and returns the result. The syntax for the call is % [a, b] = swap (a, b) where the a and b in the ( ) are the % values sent to the function and the a and b in the [ ] are % returned values which are assigned to corresponding % variables in your program. temp=a; a=b; b=temp; Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    12. 12. Engineering H192 - Computer Programming Example of a MATLAB Function File • To use the function a MATLAB program could assign values to two variables (the names do not have to be a and b) and then call the function to swap them. For instance the MATLAB commands: >> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y ) result in: x= 6 y= 5 Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    13. 13. Engineering H192 - Computer Programming MATLAB Function Files • Referring to the function, the comments immediately following the function definition statement are the "help" for the function. The MATLAB command: >>help swap %displays: The function swap receives two values, swaps them, and returns the result. The syntax for the call is [a, b] = swap (a, b) where the a and b in the ( ) are the values sent to the function and the a and b in the [ ] are returned values which are assigned to corresponding variables in your program. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    14. 14. Engineering H192 - Computer Programming MATLAB Function Files • The MATLAB function must be in the current working directory. If it is not, the directory must be changed before calling the function. • If MATLAB cannot find the function or its syntax does not match the function call, an error message will appear. Failure to change directories often results in the error message: Undefined function or improper matrix assignment. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    15. 15. Engineering H192 - Computer Programming MATLAB Function Files • When the function file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a: % Make a: the current working directory Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    16. 16. Engineering H192 - Computer Programming MATLAB Function Files • Unlike C, a MATLAB variable does not have to be declared before being used, and its data type can be changed by assigning a new value to it. • For example, the function factorial ( ) on the next slide returns an integer when a positive value is sent to it as an argument, but returns a character string if the argument is negative. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
    17. 17. Engineering H192 - Computer Programming MATLAB Function Files function [n] = factorial (k) % The function [n] = factorial(k) calculates and % returns the value of k factorial. If k is negative, % an error message is returned. if (k < 0) n = 'Error, negative argument'; elseif k<2 n=1; else n = 1; for j = [2:k] n = n * j; end end Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19

    ×