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

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Chapter 3: Editing and Debugging SAS Programs. Some useful tips of using Program Editor Add line number: In the Command Box, type num, enter. Save SAS.
Programming with MATLAB
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Automating Tasks With Macros
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
Guide To UNIX Using Linux Third Edition
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
Digital Image Processing Lecture3: Introduction to MATLAB.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
January 24, 2005 Lecture 3 - By P. Lin 1 CPET 190 Lecture 3 Problem Solving with MATLAB
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
MATLAB File Management. MATLAB User File Management Matlab provides a group of commands to manage user files. For more information, type help iofun. pwd.
Introduction to Shell Script Programming
Fortran 1- Basics Chapters 1-2 in your Fortran book.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
1 Tips for solving Project 1 Reactor SO 3 SO 2 +O 2.
Copyright © 2007, Oracle. All rights reserved. Managing Concurrent Requests.
Recap Graphic Window Edit Window Start Button Matrices in MATLAB Scalar Operations Order of Operations Array Operations Matrix Addition Matrix Multiplication.
Shell Scripting Introduction. Agenda What is Shell Scripting? Why use Shell Scripting? Writing and Running a Shell Script Basic Commands -ECHO - REM.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
Copyright © The McGraw-Hill Companies, Inc. Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 1 An Overview of MATLAB.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Linux Operations and Administration
Shell Programming. Introducing UNIX Shells  Shell is also a programming language and provides various features like variables, branching, looping and.
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Introduction to MATLAB 7 Engineering 161 Engineering Practices II Joe Mixsell Spring 2010.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
Introduction to Engineering MATLAB – 2 Introduction to MATLAB - 2 Agenda Defining Variables MATLAB Windows.
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
CMPS 1371 Introduction to Computing for Engineers MatLab.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
Introduction to MATLAB 7 MATLAB Programming for Engineer Hassan Migdadi Spring 2013.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Introduction to MATLAB 7 Engineering 161 Engineering Practices II Joe Mixsell Spring 2012.
Today we will learn MATLAB Click Start  All programm  Class Software  Matlab This command window will be seen with a prompt sign >> Any command can.
Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement.
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Matlab for Engineers Matlab Environment Chapter 2.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
ENG College of Engineering Engineering Education Innovation Center 1 Functions 1 in MATLAB Topics Covered: 1.Uses of Functions Organizational Tool.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Release Numbers MATLAB is updated regularly
Matlab Training Session 4: Control, Flow and Functions
CS1371 Introduction to Computing for Engineers
Use of Mathematics using Technology (Maltlab)
MATLAB – What Is It ? Name is from matrix laboratory Powerful tool for
MATLAB – What Is It ? Name is from matrix laboratory Powerful tool for
Coding Concepts (Basics)
Digital Image Processing
Presentation transcript:

Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1

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

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

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

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

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, ]; 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

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

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

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

% 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

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

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

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

Here is an example that shows how to use the function sinelimit : >> sinelimit(5) ans = 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

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!,

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

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

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