Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.

Similar presentations


Presentation on theme: "Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1."— Presentation transcript:

1 Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1

2 2 1- M-Files 2- Script M-Files 2.1- Echoing Commands 2.2- Adding Comments 2.3- Structuring Script M-Files 3- Function M-Files 4- Loops 5- Fine-Tuning Your M-Files 6- Branching with if

3 1- M-Files For complicated problems, the simple editing tools provided by the Command Window and its history mechanism are insufficient. A much better approach is to create an M-file. There are two different kinds of M-files: script M-files and function M-files. M-files are ordinary text files containing MATLAB commands. You can create and modify them using any text editor or word processor that is capable of saving files as plain ASCII text. (Such text editors include notepad in Windows). More conveniently, you can use the built-in Editor/Debugger, which you can start by typing edit, either by itself (to edit a new file) or followed by the name of an existing M-file in the current working directory. You can also use the File menu or the two leftmost buttons on the tool bar to start the Editor/Debugger, either to create a new file or to open an existing file. Double-clicking on an M-file in the Current Directory browser will also open it in the Editor/Debugger. 3

4 2- Script M-Files Suppose you want to calculate the values of: sin(0.1)/0.1, sin(0.01)/0.01, and sin(0.001)/0.001 to 15 digits. Such a simple problem can be worked directly in the Command Window. Here is a typical first try at a solution, together with the response that MATLAB displays in the Command Window: >> x = [0.1, 0.01, 0.001]; >> y = sin(x)./x y = 0.9983 1.0000 1.0000 After completing a calculation, you will often realize that the result is not what you intended. The commands above displayed only 5 digits, not 15. To display 15 digits, you need to type the command format long and then repeat the line that defines y. 4

5 In this case you could simply retype the latter line, but in general retyping is time consuming and error prone, especially for complicated problems. How can you modify a sequence of commands without retyping them? You could construct a script M-file to solve the mathematical problem described earlier. Create a file containing the following lines: format long x = [0.1, 0.01, 0.001]; y = sin(x)./x Save this file with the name task1.m in your working directory, or in some directory on your path. You can name the file any way you like (subject to the usual naming restrictions on your operating system), but the “.m ” suffix is mandatory. 5

6 You can tell MATLAB to run (or execute) this script by typing task1 in the Command Window. (You must not type the “.m ” extension here; MATLAB automatically adds it when searching for M-files.) The output — but not the commands that produce them — will be displayed in the Command Window. Now the sequence of commands can easily be changed by modifying the M-file task1.m. For example, if you also wish to calculate sin(0.0001)/0.0001, you can modify the M-file to read format long x = [0.1, 0.01, 0.001, 0.0001]; y = sin(x)./x and then run the modified script by typing task1. Be sure to save your changes to task1.m first; otherwise, MATLAB will not recognize them. 6

7 2.1- Echoing Commands The commands in a script M-file will not automatically be displayed in the Command Window. If you want the commands to be displayed along with the results, use echo : echo on format long x = [0.1, 0.01, 0.001]; y = sin(x)./x echo off 2.2- Adding Comments It is worthwhile to include comments in a lengthly script M-file. These comments might explain what is being done in the calculation, or they might interpret the results of the calculation. 7

8 Any line in a script M-file that begins with a percent sign is treated as a comment and is not executed by MATLAB. Here is our new version of task1.m with a few comments added: echo on % Turn on 15 digit display format long x = [0.1, 0.01, 0.001]; y = sin(x)./x % These values illustrate the fact that the limit of % sin(x)/x as x approaches 0 is 1. echo off When adding comments to a script M-file, remember to put a percent sign at the beginning of each line. This is particularly important if your editor starts a new line automatically while you are typing a comment. If you use echo on in a script M-file, then MATLAB will also echo the comments, so they will appear in the Command Window. 8

9 2.3- Structuring Script M-Files For the results of a script M-file to be reproducible, the script should be self- contained, unaffected by other variables that you might have defined elsewhere in the MATLAB session, and uncorrupted by leftover graphics. With this in mind, you can type the line clear all at the beginning of the script, to ensure that previous definitions of variables do not affect the results. You can also include the close all command at the beginning of a script M- file that creates graphics, to close all graphics windows and start with a clean slate. Here is our example of a complete, careful, commented solution to the problem described above: % Remove old variable definitions clear all % Remove old graphics windows close all % Display the command lines in the command window echo on % Turn on 15 digit display format long 9

10 % Define the vector of values of the independent variable x = [0.1, 0.01, 0.001]; % Compute the desired values y = sin(x)./x % These values illustrate the fact that the limit of % sin(x)/x as x approaches 0 is equal to 1. echo off Sometimes you may need to type, either in the Command Window or in an M-file, a command that is too long to fit on one line. If so, when you get near the end of a line you can type... (that is, three successive periods) followed by ENTER, and continue the command on the next line. In the Command Window, you will not see a command prompt on the new line. 10

11 3- Function M-Files You often need to repeat a process several times for different input values of a parameter. For example, you can provide different inputs to a built-in function to find an output that meets a given criterion. As you have already seen, you can use inline to define your own functions. In many situations, however, it is more convenient to define a function using an M-file instead of an inline function. Let us return to the problem described above, where we computed some values of sin(x)/x with x = 10 -b for several values of b. Suppose, in addition, that you want to find the smallest value of b for which sin(10 -b )/(10 -b ) and 1 agree to 15 digits. Here is a function M-file called sinelimit.m designed to solve that problem: 11

12 function y = sinelimit(c) % SINELIMIT computes sin(x)/x for x = 10ˆ(-b), % where b = 1,..., c. format long b = 1:c; x = 10.ˆ(-b); y = (sin(x)./x)’; Like a script M-file, a function M-file is a plain text file that should reside in your MATLAB working directory. The first line of the file contains a function statement, which identifies the file as a function M-file. The first line specifies the name of the function and describes both its input arguments (or parameters) and its output values. In this example, the function is called sinelimit. The file name and the function name should match. 12

13 The function sinelimit takes one input argument and returns one output value, called c and y (respectively) inside the M-file. When the function finishes executing, its output will be assigned to ans (by default) or to any other variable you choose, just as with a built-in function. The remaining lines of the M-file define the function. In this example, b is a row vector consisting of the integers from 1 to c. The vector y contains the results of computing sin(x)/x where x = 10 -b ; the prime makes y a column vector. Notice that the output of the lines defining b, x, and y is suppressed with a semicolon. In general, the output of intermediate calculations in a function M-file should be suppressed. 13

14 Here is an example that shows how to use the function sinelimit : >> sinelimit(5) ans = 0.99833416646828 0.99998333341667 0.99999983333334 0.99999999833333 0.99999999998333 None of the values of b from 1 to 5 yields the desired answer, 1, to 15 digits. Judging from the output, you can expect to find the answer to the question we posed above by typing sinelimit(10). Try it! 14

15 4- Loops A loop specifies that a command or group of commands should be repeated several times. The easiest way to create a loop is to use a for statement. Here is a simple example that computes and displays 10! = 10 · 9 · 8 · · · 2 · 1: f = 1; for n = 2:10 f = f*n; end f The loop begins with the for statement and ends with the end statement. The command between those statements is executed a total of nine times, once for each value of n from 2 to 10. We used a semicolon to suppress intermediate output within the loop. To see the final output, we then needed to type f after the end of the loop. Without the semicolon, MATLAB would display each of the intermediate values 2!, 3!,.... 15

16 5- Fine-Tuning Your M-Files You can edit your M-file repeatedly until it produces the desired output. Generally, you will run the script each time you edit the file. If the program is long or involves complicated calculations or graphics, it could take a while each time. Then you need a strategy for debugging. Here are some general tips: 1- Include clear all and close all at the beginning of the M-file. 2- Use echo on early in your M-file so that you can see “cause” as well as “effect”. 3- If you are producing graphics, use hold on and hold off carefully. In general, you should put a pause statement after each hold off. Otherwise, the next graphics command will obliterate the current one, and you won’t see it. 4- Do not include bare print statements in your M-files. Instead, print to a file. 5-Make liberal use of pause. 16

17 6- Finally, remember that you can stop a running M-file by typing CTRL+C. This is useful if, at a pause or input statement, you realize that you want to stop execution completely. 6- Branching with if For a simple illustration of branching with if, consider the following function M-file absval.m, which computes the absolute value of a real number: function y = absval(x) if x >= 0 y = x; else y = -x; end 17

18 The first line of this M-file states that the function has a single input x and a single output y. If the input x is nonnegative, the if statement is determined by MATLAB to be true. Then the command between the if and the else statements is executed to set y equal to x, while MATLAB skips the command between the else and end statements. However, if x is negative, then MATLAB skips to the else statement and executes the succeeding command, setting y equal to -x. In general, if must be followed on the same line by an expression that MATLAB will test to be true or false. 18


Download ppt "Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1."

Similar presentations


Ads by Google