What We Will Learn Today

Similar documents
Introduction to Matlab

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

Fall 2014 MAT 375 Numerical Methods. Introduction to Programming using MATLAB

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

ENGR 1181 MATLAB 05: Input and Output

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

1) As a logical statement, is 1 considered true or false in MATLAB? Explain your answer.

What is MATLAB and howtostart it up?

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

Desktop Command window

FreeMat Tutorial. 3x + 4y 2z = 5 2x 5y + z = 8 x x + 3y = -1 xx

Introduction to Matlab

1) As a logical statement, is 1 considered true or false in MATLAB? Explain your answer.

Control Structures. March 1, Dr. Mihail. (Dr. Mihail) Control March 1, / 28

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Chapter 4: Programming with MATLAB

LECTURE 1. What Is Matlab? Matlab Windows. Help

Computer Packet 1 Row Operations + Freemat

Introduction to Programming for Biology Research

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Introduction to Matlab. By: Hossein Hamooni Fall 2014

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Digital Image Analysis and Processing CPE

Matlab Review. Dr. Mark Glauser, Created by: David Marr. Mechanical Engineering Syracuse University. Matlab Review p.

function [s p] = sumprod (f, g)

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction to programming in MATLAB

MATLAB GUIDE UMD PHYS401 SPRING 2012

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Introduction to MATLAB

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Introduction to MATLAB

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Intro to Matlab for GEOL 1520: Ocean Circulation and Climate or, Notions for the Motions of the Oceans

MATLAB for Experimental Research. Fall 2018 Vectors, Matrices, Matrix Operations

7 Control Structures, Logical Statements

SIMPLE INPUT and OUTPUT:

Array Accessing and Strings ENGR 1187 MATLAB 3

Chapter 3: Programming with MATLAB

Lecture 2 Introduction to MATLAB. Dr.Tony Cahill

LAB 2: Linear Equations and Matrix Algebra. Preliminaries

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

Files and File Management Scripts Logical Operations Conditional Statements

x = 12 x = 12 1x = 16

1 Overview of the standard Matlab syntax

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

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

To see what directory your work is stored in, and the directory in which Matlab will look for files, type

Array Accessing and Strings ENGR 1181 MATLAB 3

Lecturer: Keyvan Dehmamy

MATLAB TUTORIAL WORKSHEET

Why use MATLAB? Mathematcal computations. Used a lot for problem solving. Statistical Analysis (e.g., mean, min) Visualisation (1D-3D)

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.

How to Use MATLAB. What is MATLAB. Getting Started. Online Help. General Purpose Commands

Introduction to MATLAB

An Introduction to MATLAB

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson)

CS 221 Lecture. Tuesday, 13 September 2011

Lab 1 Intro to MATLAB and FreeMat

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

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

2.0 MATLAB Fundamentals

Introduction to MATLAB

To start using Matlab, you only need be concerned with the command window for now.

Mini-Matlab Lesson 5: Functions and Loops

Compact Matlab Course

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

Outline. User-based knn Algorithm Basics of Matlab Control Structures Scripts and Functions Help

Teaching Manual Math 2131

MATLAB GUIDE UMD PHYS401 SPRING 2011

Introduction to MATLAB

The Mathematics of Big Data

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

CM0340 Tutorial 2: More MATLAB

Introduction to MATLAB

Array Creation ENGR 1181 MATLAB 2

AN INTRODUCTION TO MATLAB

ECE 102 Engineering Computation

ARRAY VARIABLES (ROW VECTORS)

Computational Photonics, Seminar 01 on Introduction into MATLAB, Page 1

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

Grace days can not be used for this assignment

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011

Digital Image Processing

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

MATLAB Introduction to MATLAB Programming

INTRODUCTION TO MATLAB PROGRAMMING Lec 1.1: MATLAB Basics

MATLAB GUIDE UMD PHYS375 FALL 2010

Programming in MATLAB Part 2

Introduction to MATLAB LAB 1

MATLAB Part 1. Introduction

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Introduction to MATLAB

Computational Mathematics

Lab 0a: Introduction to MATLAB

CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t.

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

Transcription:

Lecture Notes 11-19-09 ENGR 0011 - Dr. Lund What we ve learned so far About the MATLAB environment Command Window Workspace Window Current Directory Window History Window How to enter calculations (and suppress output with ;) How to use variable names Basic mathematical functions in MATLAB How to enter and manipulate arrays in MATLAB How to perform matrix operations versus element-by-element array operations ( + - * ) versus ( + -.*./.^ ) How to enter and manipulate arrays in MATLAB (Section 4.6) What We Will Learn Today Getting program input using load and input commands Loading external data (Section 4.8) Getting input from program user (Section 4.11.3) Creating MATLAB programs in script (.m) files Program processing structures: If Statements (Section 4.10.3) Loops (Section 4.10.4) Using MATLAB to solve Simultaneous Linear Equations (Section 4.11) NOTE: The material presented in these lecture notes does not Program output summary completely follow in the same order as the book. It is presented to facilitate completing Assignment 11 Loading Data from External Files Command: load filename.txt What does this command do? Loads data from filename.txt into an array variable called filename Data file must be an ASCII text file 1

Different Ways of Loading Data Files What if we had a different data file name? How can we use the load command differently such that we only have to modify one line if the file name is different? load ( lineq.dat ) How can we capture the result of this command? system = load ( lineq.dat ) What happens if we assign the name of a data file as a string to a variable? filename = lineq.dat Can the variable filename be used in the load command? YES: system = load(filename) Creating and Running Script Files Save your script as filename.m in your current directory note change of extension You have just created a MATLAB script In the MATLAB command window, type» filename How to allow your program to run with any user-entered file name Create a data file (.dat or.txt) which contains the A matrix and b vector for a system of equations, where data is stored such that the A and b matrices are next to each other, i.e. the first row contains the first row of the A matrix and the first element of the b vector. The number of rows will therefore be the same as the number or unknowns for the system of equation, and the number of columns will be one greater than the number of rows How would you load this data file? filename=input( Enter file name:, s ); system = load(filename) 2

Separating Data Use of COLON (:) in array extraction With the data loaded and stored to the variable system (or whatever variable name you choose), how would you obtain A and b? For a system of 3 equations A = system ( :, 1:3 ) This translates to extracting all of the rows in columns 1-3 b = system ( :, 4 ) This translates to extracting all of the rows in column 4 How to allow your program to run with any size data file How could you modify a MATLAB program to be able to determine if data from file was stored horizontally or vertically? By determining the number of rows vs. number of columns MATLAB Command: size(matrix) What does size(lineq) give you? How many outputs are there? What are the outputs How can we assign the outputs to variables? [rows, cols] = size(system) Obtaining Input from User In Matlab, command is: input To acquire numerical input AGE = input ( How old are you? ) To acquire string (text) input MONTH = input ( What is your name?, s ) Notice additional argument ( s ) required for string input 3

Summary Input Statements input var_no = input( What? ); var_str = input( What?, s ); load load dataset.txt loads data from a text file and assigns to variable called dataset filename = input( Type in data file, s ) data = load(filename) - assigns data from text file to variable called data The use of the : argument to define variables Using MATLAB to Solve Ax=b Given the following equations, how would you represent them as a linear system of equations: 3x + 5z = 2y z = 2y 8 4(x + y) = 2(0.5 - z) How would you represent these equations in matrix form, A*x = b? 3 2 5 x 0 A 0 2 1 x y b 8 4 4 2 z 1 Why? (i.e. what do you get when you multiply A*x?) 3x 2y + 5z = 0 0x + 2y - z = 8 4x + 4y + 2z = 1 Using MATLAB to Solve Ax=b How do you solve a linear system of equations in MATLAB? Matrix Operations A * x = b A -1 * A * x = A -1 * b I * x = A -1 *b x = A -1 * b MATLAB Command: inv(a) Test the following What is inv(a) * A? Let I = inv(a)*a What s I * b? What does that prove? 4

Using MATLAB to Solve Ax=b What if data file was loaded vertically, i.e. such that all the x coefficients were in first row, y coefficients in second row, z coefficients in third row, and b vector in fourth row? MATLAB transpose command: A Atrans = system ( 1:rows 1, : ) A = Atrans brow = system ( rows, : ) b = brow 3 A 0 4 2 2 4 5 3 1 A' 2 2 5 Transposing 0 2 1 4 4 2 Using MATLAB to Solve Ax=b Create M-file which loads program, determines if system of equations is stored horizontally or vertically, then determine A, b, x accordingly if (cols-rows) == 1 A = lineq ( :, 1:cols-1 ) b = lineq( :, cols ) x = inv(a) * b elseif (rows-cols) == 1 Atrans = lineq ( 1:rows-1, : ) A = Atrans' btrans = lineq ( rows, : ) b = b' x = inv(a) * b else disp('error in data set') Program Branching: If Statements Branching gives a program the ability to make decisions based on specified data or user input A program makes the decisions using relational and logical operations Relational operators: < <= > >= ~= == Logical operators: & (and) (or) ~ (not) To specify a decision point in Matlab, the if statement is used as follows condition if x <= 0 flag = 1 statement required to indicate of structure Statement(s) evaluated if condition is TRUE 5

One Conditional If Statement if condition statement 1 statement 2 FALSE If (condition) Enter if structure TRUE Execution of Command Statements Exit if structure IF - ELSE Statement Enter if structure if condition statement 1 statement 2 else statement 1 statement 2 FALSE Execution of else Command Statements If (condition) TRUE Execution of Command Statements Exit if structure Multiple Conditions: IF ELSEIF - ELSE Statement if (condition 1) statements elseif (condition 2) statements elseif (condition 3) statements elseif (condition 4) statements else statements 6

Example Create a Matlab script (M-file) to acquire users age then specify what decade they were born Note indenting of statements in if structure Note new command: disp How does the output of disp differ from when ; is not used? age = input ('How old are you? '); if age <= 6 disp('wow, you are a 21st Century child!') elseif age > 6 & age <= 16 decade = '1990s'; else disp('you are too old to tell. Sorry.') disp('you were born in ') disp(decade) Loop Structures: While & For Loop structures can be used in a program to execute a block of statements multiple times The number of times the statements are executed can be specified (for loop), or can be unspecified and based on a condition (while loop) for x = [1 2 3 4 5] statement 1 statement 2 while x < 5 statement 1 statement 2 While Loops Enter loop FALSE While (condition) TRUE Exit loop Execution of Command Statements 7

Examples of Where a While Loop Could be Used To have program run again if requested To Count Example: Write a short program which counts by 2s (The concept of counting can be used in a number of ways to keep track of how many times a while loop has run, and to then make use of that count) To keep a running sum (similar to counting ) Example: Write a short program which allows user to sum a series of numbers Example Question Example Let s modify our previous file by adding a while loop to allow the user to run the program again again = 1; while again == 1 age = input ('How old are you? '); if age <= 4 disp('wow, you are a 21st Century child!') elseif age > 4 & age <= 14 decade = '1990s'; else disp('you are too old to tell. Sorry.') disp('you were born in ') disp(decade) again = input('type the number 1 to run again, 0 to stop: '); 8

Using Strings with IF & WHILE Conditions What is the problem with the following code? month = input('what is your birth month?','s'); if month == 'January' disp('your birthstone is Garnet') elseif month == 'February' disp('your birthstone is Amethyst') elseif month == 'March' abc == defghij is like comparing [1 2 3] == [1 2 3 4 5 6] Strings are arrays of characters. To use strings in logic comparisons, dimensions must agree Logical Comparison of Arrays in MATLAB Numbers 4 == 4 Ans = 1 (1 ~ True) 4 == 2 Ans = 0 (0 ~ False) 4 == [ 4 3 2] (OK) Ans = 1 0 0 4 is treated as scalar and compared to each component of array [4 3] == [4 3 2 1] ERROR: Matrix dimensions must agree Strings y == y Ans = 1 (1 ~ True) y == n Ans = 0 (0 ~ False) y == yes (OK) Ans = 1 0 0 y is treated as scalar characterand compared to each component of array no == yes ERROR: Array dimensions must agree How is this related to dummy proofing user input? doagain = 'y'; while doagain == 'y' doagain == 'Y' disp( While loop executing') doagain = input('would you like to run this program again? y/n: ','s '); while doagain ~='y' & doagain ~='Y' & doagain ~='n' & doagain ~='N disp('error: You must respond with a single character, y or n') doagain = input('would you like to run this program again? y/n: ','s'); This code works fine as long as user types in a single character. Problem occurs when user responds with yes. Program terminates without error ( yes ~= y gives [0 1 1] which is FALSE) leaving user wondering what happened. 9

Fix to problem in previous slide doagain = 'y'; while doagain(1) == 'y' doagain(1) == 'Y % Enter program commands here doagain=input('run again?','s'); while doagain(1) ~= 'y' & doagain(1)~= 'Y' & doagain(1)~= 'n' & doagain(1) ~= 'N' doagain=input('error: You must respond with a y or n:, s ) This would NOT work doagain = 'y'; while doagain == 'y' doagain == 'Y doagain == yes doagain == YES disp( While loop executing') doagain = input('would you like to run this program again? y/n: ','s '); This code works ok as long as user types in a single character or 3 character response (i.e. y n or yes ). Program Error occurs when user responds with no, which causes a 2 character array to be compared to a 3 character array in while condition. Commands Learned Input commands load Input uigetfile * : Output commands disp ; save * Programming structures if else elseif - while - * = See textbook and review on your own 10