MATLAB Introduction to MATLAB Programming MATLAB Scripts So far we have typed all the commands in the Command Window which were executed when we hit Enter. Although every MATLAB command can be executed in this way, using the Command Window to execute a series of commands is not convenient and may be difficult (or even impossible). A better way of executing a sequence of commands is first to create a file with a list of commands, save it, and then run (execute) the file. When the file runs, the commands it contains are executed in the order that they are listed. If needed, the commands in the file can be corrected or changed and the file can be saved and run again. Files that are used for this purpose are called script files. Notes About Script Files A script file is a sequence of MATLAB commands, also called a program. When a script file runs (is executed), MATLAB executes the commands in the order they are written, just as if they were typed in the Command Window. When a script file has a command that generates an output, say an assignment of a value to a variable (without a semicolon at the end), the output is displayed in the Command Window. Using a script file is convenient because it can be edited (corrected or otherwise changed) and executed many times. Script files can be typed and edited in any text editor. Script files are also called M-files because the extension.m is used when they are saved. Creating and Saving a Script File In MATLAB script files are created and edited in the Editor/Debugger Window. This window is opened from the Command Window by clicking on the New Script icon in the Toolstrip, or by clicking New in the Toolstrip and then selecting Script from the menu that open. Before a script file can be executed it has to be saved. MATLAB adds the extension.m to the name. The rules for naming a script file follow the rules of naming a variable (must begin with a letter, can include digits and underscore, no spaces, and up to 63 characters long). The names of user-defined variables, predefined variables, and MATLAB commands or functions should not be used as names of script files. Running (Executing) a Script File A script file can be executed either directly from the Editor Window by clicking on the Run icon or by typing the file name in the Command Window and hitting Enter. For a file to be executed, MATLAB needs to know where the file is saved. The file will be executed if the folder where the file is saved is the current folder of MATLAB or if the folder is listed in the search path. Current Folder The current folder is shown in the "Current Folder" field in the desktop toolbar of the Command Window. Once two or more different current folders are used in a session, it is possible to switch from one to another in the Current Folder field in the Command Window. You old dos (or Linux) users, can simply use the cd command in the command window.
Remarks You have already seen that the % character is a comment in MATLAB. You will want to wellcomment your code. The first comment at the beginning of the script describes what the script does, when you type >>EDU help scriptname in the command window. You can also use block comments: %{ lots of comments here.................. %} The disp Command The disp command is used to display the elements of a variable without displaying the name of the variable, and to display text. The format of the disp command is: disp(name of a variable) or disp('text as string') Every time the disp command is executed, the display it generates appears in a new line. Only one variable can be displayed in a disp command. If elements of two variables need to be displayed together, a new variable (that contains the elements to be displayed) must first be defined and then displayed. In many situations it is nice to display output (numbers) in a table. This can be done by first defining a variable that is an array with the numbers and then using the disp command to display the array. The fprintf Command The fprintf command can be used to display output (text and data) on the screen or to save it to a file. With this command (unlike with the disp command) the output can be formatted. For example, text and numerical values of variables can be intermixed and displayed in the same line. In addition, the format of the numbers can be controlled. fprintf( text typed in as a string ) With the fprintf command it is possible to start a new line in the middle of the string. This is done by inserting \n before the character that will start the new line. The \n is called an escape character. It is used to control the display. Other escape characters are: \b Backspace. \t Horizontal tab.
To display a mix of text and a number (value of a variable), the fprintf command has the form: fprintf( text as string %-5.2f additional text, variable_name) The % sign marks the spot where the number is inserted within the text. Formatting elements (define the format of the number). The name of the variable whose value is displayed. The formatting elements are: -5.2f Flag Field width and precision Conversion character The flag, which is optional, can be one of the following three characters: (minus sign) Left-justifies the number within the field. + (plus sign) Prints a sign character (+ or ) in front of the number. 0 (zero) Adds zeros if the number is shorter than the field. The field width and precision (the 5.2 above) are optional. The first number (5 in the example) is the field width, which specifies the minimum number of digits in the display. If the number to be displayed is shorter than the field width, spaces or zeros are added in front of the number. The precision is the second number (2 in the example). It specifies the number of digits to be displayed to the right of the decimal point. The conversion character is the last element in the formatting elements (the f in the example above), which is required, and specifies the notation in which the number is displayed. Some common notations: f - float; fixed-point notation ( 17.090980). e - Exponential notation using lowercase e ( 1.709098e+001). c - A single character. s - A string of characters. g - The shorter of e or f notations. d or i - Integer. Additional remarks about the fprintf command: To place a single quotation mark in the displayed text, type two single quotation marks in the string inside the command. The fprintf command is vectorized. This means that when a variable that is a vector or a matrix is included in the command, the command repeats itself until all the elements are displayed. If the variable is a matrix, the data is used column by column.
The Input Function When a script file is executed, the variables that are used in the file must have assigned values (in the workspace). The assignment of a value to a variable can be done in three ways: 1. The variable is defined and assigned a value in the script file. 2. The variable is defined and assigned a value in the Command Window. 3. The variable is defined in the script file, but a specific value is entered in the Command Window when the script file is executed. Cases 1, and 2, we have seen, case 3 is new and requires the use of the input function. The variable is defined in the script file, and when the file is executed, the user is prompted to assign a value to the variable in the Command Window. The form of the input command is: variable_name = input( string that is displayed in the Command Window ) The user types the value and presses the Enter key. This assigns the value to the variable. For example: T=input('Enter the temperature in F: '); Simple Plots The plot command is used to create two-dimensional plots. The simplest form of the command is: plot(x,y) where both x and y are vectors. The two vectors must have the same number of elements. When the plot command is executed, a figure is created in the Figure Window. If not already open, the Figure Window opens automatically when the command is executed. The figure has a single curve with the x values on the horizontal axis and the y values on the vertical axis. The curve is constructed of straight-line segments that connect the points whose coordinates are defined by the elements of the vectors x and y. Each of the vectors, of course, can have any name. The vector that is typed first in the plot command is used for the horizontal axis, and the vector that is typed second is used for the vertical axis. The plot command has additional, optional arguments that can be used to specify the color and style of the line and the color and type of markers, if any are desired; has the form: plot(x,y, line types, PropertyName,PropertyValue) Line types: Line specifiers are optional and can be used to define the style and color of the line and the type of markers (if markers are desired). The line types are: -- dashed -. dash dot : dotted - solid
If no line type is specified, a solid line is drawn between the points. The possible colors are: b blue c cyan g green k black m magenta r red w white y yellow Either the single character listed above or the full name of the color can be used to specify the color. The plot symbols, or markers, that can be used are:. point o circle x x- mark + plus * star s square d diamond v down triangle ^ up triangle < left triangle > right triangle h hexagram p pentagram clf - clears the Figure Window by removing everything from it. figure - creates a new, empty Figure Window when called without any arguments. Calling it as figure( n) where n is an integer is a way of creating and maintaining multiple Figure Windows, and of referring to each individually. hold - is a toggle that freezes the current graph in the Figure Window, so that new plots will be superimposed on the current one. Just hold by itself is a toggle, so calling this function once turns the hold on, and then the next time turns it off. Alternatively, the commands hold on and hold off can be used. legend - displays strings passed to it in a legend box in the Figure Window in order of the plots in the Figure Window grid - displays grid lines on a graph. Called by itself, it is a toggle that turns the grid lines on and off. Alternatively, the commands grid on and grid off can be used.
The save and load Commands The save command is used for saving the variables (all or some of them) that are stored in the workspace. The two simplest forms of the save command are: save file_name and save('file_name') When either one of these commands is executed, all of the variables currently in the workspace are saved in a file named: file_name.mat (created in the current directory). In mat files, which are written in a binary format, each variable preserves its name, type, size, and value. These files cannot be read by other applications. The save command can also be used for saving in ASCII format, which can be read by applications outside MATLAB. Saving in ASCII format is done by adding the argument -ascii in the command, for example: save file_name -ascii In the ASCII format the variable s name, type, and size are not preserved. The data is saved as characters separated by spaces but without the variable names. Reading from a file is accomplished using load. The load command can be used for retrieving variables that were saved with the save command back to the workspace, and for importing data that was created with other applications and saved in ASCII format or in text (.txt) files. Variables that were saved with the save command in.mat files can be retrieved with the command: load file_name and load('file_name') The load command can also be used to import data that is saved in ASCII or text (.txt) to the workspace. This is possible only if the data in the file is in the form of a variable in MATLAB. Thus, the file can have one number (scalar), a row or a column of numbers (vector), or rows with the same number of numbers in each (matrix). When data is loaded from an ASCII or text file into the workspace, it has to be assigned to a variable name. Data in ASCII format can be loaded with either of the following: load file_name or VarName=load('file_name') If the data is in a text file, the extension.txt has to be added to the file name. The form command is: load file_name.txt VarName=load('file_name.txt')
Function Definitions A function in MATLAB that returns a single result consists of the following. The function header (the first line), comprised of (see example below): the reserved word function the name of the output argument followed by the assignment operator (=), as the function returns a result the name of the function (important: this should be the same as the name of the M-file in which this function is stored to avoid confusion) the input arguments in parentheses, which correspond to the arguments that are passed to the function in the function call. A comment that describes what the function does (this is printed when help is used). The body of the function, which includes all statements and eventually must put a value in the output argument. end at the end of the function (note that this is not necessary in current versions of MATLAB, but it is considered good style anyway). The general form of a function definition for a function that returns one value looks like this: functionname.m function outputargument = functionname( input arguments) % Comment describing the function Statements here; these must include putting a value in the output argument; end