MATLAB Introduction to MATLAB Programming

Similar documents
Chapter 3: Introduction to MATLAB Programming (4 th ed.)

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

Matlab Tutorial 1: Working with variables, arrays, and plotting

Programming 1. Script files. help cd Example:

MATLAB - Lecture # 4

Desktop Command window

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

QUICK INTRODUCTION TO MATLAB PART I

Mechanical Engineering Department Second Year (2015)

ENGR 1181 MATLAB 05: Input and Output

Chapter 1 Introduction to MATLAB

PART 1 PROGRAMMING WITH MATHLAB

Importing and Exporting Data

MATLAB Introduction To Engineering for ECE Topics Covered: 1. Creating Script Files (.m files) 2. Using the Real Time Debugger

Programming in Mathematics. Mili I. Shah

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

Additional Plot Types and Plot Formatting

1 Introduction to Matlab

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

Introduction to MATLAB Programming

This module aims to introduce Precalculus high school students to the basic capabilities of Matlab by using functions. Matlab will be used in

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression.

Introduction to Matlab

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College

MAT 275 Laboratory 1 Introduction to MATLAB

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

MATLAB SUMMARY FOR MATH2070/2970

Introduction to MATLAB

Matlab Programming Arrays and Scripts 1 2

PROGRAMMING WITH MATLAB WEEK 13

MATLAB Tutorial III Variables, Files, Advanced Plotting

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial Vb

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab

Chapter 1: An Overview of MATLAB

Chapter 11 Input/Output (I/O) Functions

What is Matlab? A software environment for interactive numerical computations

Introduction to MATLAB LAB 1

Lecture 2 Introduction to MATLAB. Dr.Tony Cahill

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

Computer Programming ECIV 2303 Chapter 1 Starting with MATLAB Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

Graphics and plotting techniques

A Guide to Using Some Basic MATLAB Functions

Lecture 1: Hello, MATLAB!

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

PROGRAMMING WITH MATLAB WEEK 6

AMS 27L LAB #2 Winter 2009

Introduction to MATLAB

GUI Alternatives. Syntax. Description. MATLAB Function Reference plot. 2-D line plot

Purpose of the lecture MATLAB MATLAB

Introduction to MATLAB

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

Introduction to Matlab

Chapter 2. MATLAB Fundamentals

LAB 1 General MATLAB Information 1

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

ES 117. Formatted Input/Output Operations

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

Computer Programming in MATLAB

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Introductory MATLAB. Appendix A A.1 BACKGROUND A.2 STARTING WITH MATLAB. Core Topics

Introduction to Scientific Programming in MATLAB

Starting a New Matlab m.file. Matlab m.files. Matlab m.file Editor/Debugger. The clear all Command. Our Program So Far

MATLAB The first steps. Edited by Péter Vass

1. Register an account on: using your Oxford address

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

The Mathcad Workspace 7

Matlab Tutorial and Exercises for COMP61021

Getting Started with DADiSP

EE168 Lab/Homework #1 Introduction to Digital Image Processing Handout #3

Introduction to MATLAB

Lecturer: Keyvan Dehmamy

Matlab Tutorial for COMP24111 (includes exercise 1)

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

MATLAB primer for CHE 225

fplot Syntax Description Examples Plot Symbolic Expression Plot symbolic expression or function fplot(f) fplot(f,[xmin xmax])

General Information. There are certain MATLAB features you should be aware of before you begin working with MATLAB.

CSE 123. Lecture 9. Formatted. Input/Output Operations

2.0 MATLAB Fundamentals

Introduction to MATLAB

DAQFactory U3 Tutorial Getting Started with DAQFactory-Express and your LabJack U3 11/3/06

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Lesson 4 Customize the ToolBox

EGR 111 Plotting Data

ME 1020 Engineering Programming with MATLAB. Chapter 1 In-Class Assignment: 1.1, 1.3, 1.13, Topics Covered:

CME 192: Introduction to Matlab

Working with Charts Stratum.Viewer 6

L E S S O N 2 Background

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Graphics Example a final product:

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

Chapter 1 Introduction to MATLAB

MATLAB Tutorial. Primary Author: Shoumik Chatterjee Secondary Author: Dr. Chuan Li

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

Finding, Starting and Using Matlab

Transcription:

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