A = [1, 6; 78, 9] Note: everything is case-sensitive, so a and A are different. One enters the above matrix as

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

Introduction to MATLAB

Physics 326G Winter Class 2. In this class you will learn how to define and work with arrays or vectors.

A Guide to Using Some Basic MATLAB Functions

PART 1 PROGRAMMING WITH MATHLAB

Introduction to Engineering gii

Lecture 2: Variables, Vectors and Matrices in MATLAB

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

Matlab Introduction. Scalar Variables and Arithmetic Operators

Our Strategy for Learning Fortran 90

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

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

1 Introduction to Matlab

PC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.

Teaching Manual Math 2131

AN INTRODUCTION TO MATLAB

Introduction to MATLAB

Introduction to MATLAB 7 for Engineers

Programming in Mathematics. Mili I. Shah

University of Alberta

MATLAB GUIDE UMD PHYS401 SPRING 2012

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

Chapter 1 Introduction to MATLAB

Introduction to Matlab

An Introduction to Numerical Methods

Introduction to MATLAB Programming

Physics 326 Matlab Primer. A Matlab Primer. See the file basics.m, which contains much of the following.

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

Mathematical Operations with Arrays and Matrices

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

Introduction to MatLab. Introduction to MatLab K. Craig 1

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

Matlab and Octave: Quick Introduction and Examples 1 Basics

MATLAB TUTORIAL WORKSHEET

Some elements for Matlab programming

Introduction to MATLAB for Engineers, Third Edition

Introduction to Matlab

AMS 27L LAB #2 Winter 2009

Computational Finance

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

Grace days can not be used for this assignment

x = 12 x = 12 1x = 16

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

A quick Matlab tutorial

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

A very brief Matlab introduction

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

EE3TP4: Signals and Systems Lab 1: Introduction to Matlab Tim Davidson Ext Objective. Report. Introduction to Matlab

MBI REU Matlab Tutorial

MATLAB GUIDE UMD PHYS401 SPRING 2011

A GUIDE FOR USING MATLAB IN COMPUTER SCIENCE AND COMPUTER ENGINEERING TABLE OF CONTENTS

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

A QUICK INTRODUCTION TO MATLAB

How to learn MATLAB? Some predefined variables

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

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

Matlab Programming Introduction 1 2

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

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

McTutorial: A MATLAB Tutorial

Table of Laplace Transforms

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

Limits. f(x) and lim. g(x) g(x)

MATLAB Tutorial Matrices & Vectors MATRICES AND VECTORS

Introduction to MATLAB

Introduction to Matlab

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Laboratory 1 Octave Tutorial

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

Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

Identity Matrix: >> eye(3) ans = Matrix of Ones: >> ones(2,3) ans =

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

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

Introduction to MATLAB

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

1 Overview of the standard Matlab syntax

Chapter 2. MATLAB Fundamentals

1.1 calculator viewing window find roots in your calculator 1.2 functions find domain and range (from a graph) may need to review interval notation

EE 350. Continuous-Time Linear Systems. Recitation 1. 1

6.094 Introduction to MATLAB January (IAP) 2009

Matlab Tutorial. Get familiar with MATLAB by using tutorials and demos found in MATLAB. You can click Start MATLAB Demos to start the help screen.

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

Introduction to Matlab

Dr Richard Greenaway

Course Layout. Go to follow instr. Accessible within campus (only for the first download)

Matlab (Matrix laboratory) is an interactive software system for numerical computations and graphics.

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

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

ARRAY VARIABLES (ROW VECTORS)

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

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

Introduction to MATLAB for Economics

Here is a quick introduction to Matlab and a couple of its symbolic and control functions.

Lab 1 Intro to MATLAB and FreeMat

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

2.0 MATLAB Fundamentals

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

Transcription:

1 Matlab Primer The purpose of these notes is a step-by-step guide to solving simple optimization and root-finding problems in Matlab To begin, the basic object in Matlab is an array; in two dimensions, these are matrices: 1 6 A = 78 9 Note: everything is case-sensitive, so a and A are different One enters the above matrix as A = 1, 6; 78, 9 ; you can use spaces instead of commas Commas or spaces mean move to the next column in the same row, semicolons mean move to the next row The semicolon at the end of the line means do not display the result of the calculation If you instead typed Matlab would display the A matrix: where A = 1, 6; 78, 9 A = 1 6 78 9 Now imagine multiplying two matrices together: B = A B 4 1 7 8 You simply type this in Matlab and it 460 490 ans = 3750 1500 If you want to assign the answer to some other array (like C) you would type A B and this would produce 460 490 3750 1500 There are about a million things you can do to a matrix in Matlab useful ones are: Some 1

1 invert: 2 trace: inv (A) 00196 00131 01700 00022 trace (A) 10 3 compute eigenvalues: eig (A) this is a vector of the eigenvalues 17 27 4 transpose: A 1 78 6 9 5 norm: norm (A) 785356 Matlab uses the least-squares norm, which basically takes the components one at a time, squares them, sums them, and takes the square root; if you type norm (A, inf) you get the sup-norm, which is the maximum difference between any element and zero 6 solving a linear system Ax = b can be done two ways: x = inv (A) b x = A\b where \ is a shorthand for the operation invert and multiply Operations in Matlab have the following priority: 2

1 Exponentiation: Aˆn means raise A to the nth power and is done first; 2 Multiplication/Division; 3 Addition/Subtraction All calls to functions are put first, so that trace (A) ˆ2 would take the trace of A and square it, but trace (Aˆ2) would square the matrix and then take the trace Only comformable matrices can be operated on, and Matlab will tell you when it can t legally perform an operation But be warned that many Matlab functions are built to accomodate generalized operations; for example, taking the inverse of a non-square matrix will tend to return something, just likely not what you expected Some useful built in functions are: 1 exponentiation exp: exp (5) = e 5 = 14841 where is Euler s constant; 2 natural logarithm log: 1 = log (e) log (1) = 0 3 sines and cosines and all trigonometric functions as well All of these functions can be applied to arrays, in which case they go element by element To do the same with basic operations like multiplication, use the dot type: A C would create an array the same size as A and C with each element being the product of the corresponding elements in A and C For example, if 1 A = 4 and 2 9 3

then 2 A 36 whereas A 38 That should be enough to get you started Let s work out a couple of problems First, a minimization (remember that maximization is just minimizing the negative; for some reason, optimization packages all do minimization): min f (x 1, f 2 ) = { x 2 1 + x 2 } 2 x 1,x 2 This has no constraints and results in the solution (x, y) = (0, 0) How would we do this in Matlab? We would do two steps 1 Define a m-file containing the function we wish to minimize Click on the New button and choose m-file The Editor will open You define your function this way: function z = fname(x); z = x(1)ˆ2 + x(2)ˆ2; Save that file The first line says fname is the name of the function which associates the vector x with the scalar z; fname can be whatever you want, but if you use a name already being used by Matlab you lose the ability to access that file For example, if you called your function sin, you couldn t access the built-in sine function 2 Now we call the function In the Command Window type f = fname(1 1) and you will be returned the value of fname at (1, 1): f = 2 3 Finally, we will minimize the function by choosing x(1) and x (2) In the Command Window type x = fminsearch( fname,1 1,optimset( fminsearch )) and you will get back quickly x = 00; 00 fminsearch is a built-in minimization routine; the call says find the function fname and minimize it, using 1 1 as a starting place and using the default settings for fminsearch (the last term is not important at this stage, as it 4

controls the optional parts of the algorithm being used to minimize the function) Good initial guesses are helpful because they speed up the process of finding the answer and sometimes a bad guess can lead the algorithm astray When minimization is done, return the value and name it x If you change the command to x, f = fminsearch( fname,1 1,optimset( fminsearch )) it will return not only x, the maximizer, but f, the function value at that point: x = 00; 00 f = 00 When you save files, you must be sure that they are on the path that Matlab uses to search for files Use the Set Path command under File to add the folder that you save things in The path is searched from the top down, so filenames that conflict are resolved according to a first come, first serve approach, which is why you usually lose access to canned Matlab files if you use their name for your program Better not to do that Now imagine we want to solve for the solution to a nonlinear equation, like a first-order condition for minimization: The solution to this equation is x 2 x 2 3 4 = 0 x = 24076 which is not readily obtainable by hand solve systems: More generally, we would want to x 2 1 x 2 exp (x 1 ) 9 = 0 x 2 2 x 1 = 0 which has solution To solve this system: (x 1, x 2 ) = (16152, 12709) 1 create an m-file that looks like function y = fname(x); y(1) = x(1)ˆ2 - x(2)*exp(x(1)) - 90; y(2) = x(2)ˆ2 - x(1); 2 At the Command Window prompt type x = fsolve( fname,1 1,optimset( fsolve )) 5

It will return the solution as well as a message telling you either (1) Optimization terminated successfully (you have found a solution) or (2) Optimizer is converging to a solution that is not a root (meaning your initial guess was bad and you should try a different one) For single equation systems like the first example, the function fzero will be a bit faster and it allows you to specify the bounds, so that you can search only for roots between two particular points To solve one equation: 1 create an m-file function y = fname(x); y = xˆ2 - xˆ(2/3) - 4 2 At the Command Window prompt type x = fzero( fname,1 6,optimset( fzero )) Matlab will come back with the answer x = 24076 If instead of 1 6 you only specify one number (like 1) fzero will start searching near 1 but expand outward until it can t anymore Given two numbers it will stay between them Finally, we want to know how to solve constrained minimization problems: subject to min {x 1,x 2} y = 2x 1 + 6x 2 05 log (x 1 ) + 05 log (x 2 ) 20 x 1 0 x 2 0 Solving constrained minimization problems is a bit more complicated because Matlab deals with every type of constraint differently in order to exploit the fastest methods The file you will use is called fmincon It solves any problem that can be written in the form subject to min F (x) x Ax B A eq x = B eq C (x) 0 C eq (x) = 0 L x U 6

where A, B, A eq, and B eq are matrices, C and C eq are nonlinear functions, and L and U are vectors of lower and upper bounds You must specify each piece if you are using something that comes after it and pass it to fmincon in the right order That is, if you intend to have A eq in your problem you must leave spaces for A and B 1 Define your m-file and save it function y = fname(x) y = 2*x(1) + 6*x(2); 2 In the Command Window set up the matrices and the upper and lower bounds by typing A = B = Aeq = Beq = U = L = 00;00 Because the problem does not have linear constraints but does have lower bounds, we get this setup means empty matrix, which holds places for the constraints that are not present in the problem Matlab can do any operation to an empty matrix and it returns another empty matrix 3 Define an m-file for your nonlinear constraints In this case, we have only C, and be careful to write it in the right way (as a less-than sign) function C Ceq = fconstraint(x) C(1) = -20-05*log(x(1)) - 05*log(x(2)); Ceq(1) = ; 4 Now type x = fmincon( fname,1 1,A,B,Aeq,Beq,L,U, fconstraint,optimset( fmincon )) which the solution: (x 1, x 2 ) = (02345, 00781) An important feature of these built-in routines is that they can accomodate parameters passed to the functions Let s say that you want to minimize the function p 1 x 1 + p 2 x 2, an expenditure function, for many different values of p 1 and p 2 following: Then do the 7

1 Define the m-file as function y = fname(x,p); y = p(1)*x(1) + p(2)*x(2) (which can be written more compactly as p * x) 2 make the command call x = fminsearch( fname,1 1,optimset( fminsearch ),p) where p is a vector of prices you define in the Command Window In this way you can pass numbers to many different files but only need to define them in one place, which makes changing them a lot easier To get additional explanation for, say fzero, type help fzero at the Command Prompt and the comments will appear, giving you instructions on what each argument of a function means We will also have interest in plotting things in Matlab If you have two vectors x and y, say where y = x 2, and you want to plot them you simply type plot(x,y) and this a figure with the plot of x versus x 2 you can also use fplot( fname,1 10) For general functions, which would provide a plot of the function fname over the interval 1 10 Finally, scatterplots can be created where both x and y are functions of some other variable: scatter(x,y) creates a plot of dots in (x, y) space, where each coordinate is (x i, y i ) A third argument controls the size of the dots and a fourth one gives you colors Example: First create a vector x, say evenly spaced from 0 to 10 with 100 points: x = linspace(0,10,100); linspace is simply a routine that a vector of a particular size that is equally spaced between two fixed points Next, calculate y as exp (x): y = exp(x); this will do the exponentiation term by term Then plot them as above Finally, sometimes we will want to do operations within a loop A for loop is executed a fixed number of times: for i=1:100 does an operation 100 times, with the counter variable i increasing from 1 to 100 in steps of 1 You can change the increment size: for i=1:5:100 8

goes in steps of 5 You can also go downward: for i=100:-1:1 counts down in increments of 1 A while loop executes until a condition is met: while x<=10 would repeat until x was larger than 10 Both types of loops are terminated by an end statement break will jump you out of the current loop It is generally better programming practice to use while instead of for and break 9