1 / 17

MATLAB: Script and Function Files

Lect 19P. 2. Winter Quarter. 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

elinor
Download Presentation

MATLAB: Script and Function Files

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. Lect 19 P. 1 Winter Quarter MATLAB: Script and Function Files Lecture 19 Instructor notes: This set of slides covers script files and function files. These are Matlabs programming options. Instructor notes: This set of slides covers script files and function files. These are Matlabs programming options.

    2. Lect 19 P. 2 Winter Quarter 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 (>>). Instructor notes: There are two types of M-filesscript 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: There are two types of M-filesscript 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.

    3. Lect 19 P. 3 Winter Quarter 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 Instructor notes: This example demonstrates several key things about Matlab script files. Weve got the script file d13.m. In order to invoke it, Matlabs 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: This example demonstrates several key things about Matlab script files. Weve got the script file d13.m. In order to invoke it, Matlabs 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.

    4. Lect 19 P. 4 Winter Quarter 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. 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 Matlabs default search path so that files do not have to be located in the current directory. 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 Matlabs default search path so that files do not have to be located in the current directory.

    5. Lect 19 P. 5 Winter Quarter 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 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: 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.

    6. Lect 19 P. 6 Winter Quarter 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 Instructor notes: Here we have another script file exampleagain 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. Its 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: Here we have another script file exampleagain 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. Its 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.

    7. Lect 19 P. 7 Winter Quarter 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. Instructor notes: Now that weve seen a script file, were 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: Now that weve seen a script file, were 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.

    8. Lect 19 P. 8 Winter Quarter 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. 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 files 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: 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 files 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.

    9. Lect 19 P. 9 Winter Quarter 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. 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++, its the value of the variables thats being passed. Addresses are NOT passed between workspaces. 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++, its the value of the variables thats being passed. Addresses are NOT passed between workspaces.

    10. Lect 19 P. 10 Winter Quarter 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. 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: 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.

    11. Lect 19 P. 11 Winter Quarter 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; 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 as value, a is assigned bs value and temp, which is as 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 herethe 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 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 as value, a is assigned bs value and temp, which is as 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 herethe 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.

    12. Lect 19 P. 12 Winter Quarter 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 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: 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.

    13. Lect 19 P. 13 Winter Quarter 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. 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: 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.

    14. Lect 19 P. 14 Winter Quarter 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. Instructor notes: A heads up for the students and a quick reminderthe Matlab function that is being called must exist in the current working directory, or be in a directory that is specified as part of Matlabs 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, its 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 heads up for the students and a quick reminderthe Matlab function that is being called must exist in the current working directory, or be in a directory that is specified as part of Matlabs 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, its 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.

    15. Lect 19 P. 15 Winter Quarter 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 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: 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.

    16. Lect 19 P. 16 Winter Quarter 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. 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: 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.

    17. Lect 19 P. 17 Winter Quarter 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 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. 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.

More Related