MATLAB SUMMARY FOR MATH2070/2970

Similar documents
1 Introduction to Matlab

PART 1 PROGRAMMING WITH MATHLAB

Introduction to MATLAB

Introduction to Matlab

Introduction to MATLAB Practical 1

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

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

Mechanical Engineering Department Second Year (2015)

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

An Introduction to Numerical Methods

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

MATLAB Introduction to MATLAB Programming

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

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

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.

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

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

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

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

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

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

Math 375 Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau)

AMS 27L LAB #2 Winter 2009

1. Register an account on: using your Oxford address

Dr Richard Greenaway

Programming 1. Script files. help cd Example:

Introduction to MATLAB

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

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

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.

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

Introduction to Matlab

Introduction to Matlab

Introduction to MATLAB 7 for Engineers

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Chapter 2. MATLAB Fundamentals

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

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

Summer 2009 REU: Introduction to Matlab

Matlab Introduction. Scalar Variables and Arithmetic Operators

Introduction to MATLAB LAB 1

2.0 MATLAB Fundamentals

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

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

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

Introduction to MATLAB for Engineers, Third Edition

An Introduction to MATLAB

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

Introduction to Matlab

Lecturer: Keyvan Dehmamy

MATLAB/Octave Tutorial

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

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

Introduction and MATLAB Basics

Laboratory 1 Octave Tutorial

A Guide to Using Some Basic MATLAB Functions

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

Finding, Starting and Using Matlab

Introduction to Matlab

Matlab Tutorial for COMP24111 (includes exercise 1)

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Introduction to Matlab

QUICK INTRODUCTION TO MATLAB PART I

7 Control Structures, Logical Statements

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

EE 301 Signals & Systems I MATLAB Tutorial with Questions

MATLAB TUTORIAL WORKSHEET

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

1 Overview of the standard Matlab syntax

Getting started with MATLAB

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014

Desktop Command window

2 Amazingly Simple Example Suppose we wanted to represent the following matrix 2 itchy = To enter itchy in Matla

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

Computational Finance

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

A General Introduction to Matlab

Matlab and Octave: Quick Introduction and Examples 1 Basics

Learning from Data Introduction to Matlab

Introduction to MATLAB

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

Introduction to Python Practical 1

Matlab Tutorial and Exercises for COMP61021

Introduction to MATLAB

Introduction to Matlab. By: Hossein Hamooni Fall 2014

AN INTRODUCTION TO MATLAB

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

Table of Contents. Basis CEMTool 7 Tutorial

Introduction to MatLab. Introduction to MatLab K. Craig 1

What is Matlab? A software environment for interactive numerical computations

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

Appendix A: MATLAB Basics

MAT 275 Laboratory 1 Introduction to MATLAB

The value of f(t) at t = 0 is the first element of the vector and is obtained by

Vectors and Matrices. Chapter 2. Linguaggio Programmazione Matlab-Simulink (2017/2018)

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

1 Week 1: Basics of scientific programming I

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning.

Computational Modelling 102 (Scientific Programming) Tutorials

Transcription:

MATLAB SUMMARY FOR MATH2070/2970 DUNCAN SUTHERLAND 1. Introduction The following is inted as a guide containing all relevant Matlab commands and concepts for MATH2070 and 2970. All code fragments should run and produce the results described. If you find any corrections, or have suggestions for additional material please email duncan.sutherland@sydney.edu.au 2. The basics 2.1. Matlab desktop. Matlab commands may be typed directly into the command window, these are then executed by Matlab one line at a time. Matlab commands consist of either basic arithmetic calculations, calls to inbuilt, or external functions, or executing scripts. A script is a sequence of commands saved as a program. An example function is sin(x). Figure 1 is a labeled diagram of the Matlab desktop. Figure 1. 1. Command window, 2. Variables, 3. Command history, 4. Directories, 5. A description of each files, 6. Editor. Selecting commands in the command history, we can copy them directly into a script. This is useful for saving work. 2.2. Variables etc. Every calculation Matlab performs assigns a value to a variable. If a variable name is not specified, Matlab assigns the output to the default variable ans. It is important to realise that the equals sign = does not mean equal in the usual mathematical sense. Instead the expression a = b means take the value of the variable b and assign the same value to variable a. There are several types of variable, we will consider only numerical, logical, and string variables. The variable names shall consist of letters, numbers, and the underscore character (if desired). Variable names must start with a letter. For example the variable bob 1 is valid, but 1 bob, 1bob, 1

2 DUNCAN SUTHERLAND etc are not valid. It is also very unwise to give the variable the same name as an in-built function, such as sin. Most of the time you will deal with numerical valued variables. That is, the variable represents some array of numbers. Arrays may be many dimensional (limited by the total memory available.) Typically only one dimensional arrays (vectors) and two dimensional arrays (matrices) are used. Logical variables take the values TRUE or FALSE and are used for things like if-statements. Strings are variables which store text. They are assigned using inverted commas(the character you get by pressing the key to the left of the enter key). For example silly= this is a string ; Strings are used for text labels, for example the title of a plot. 2.3. Simple operations. The arithmetic operators + addition, subtraction, multiplication division, ˆ raising-to-a-power are fairly intuitive. Be aware that Matlab expects matrices by default. Hence, multiplication and raising-to-a-power only work for square matrices, and may not give the result you expect. Typically, when we multiply arrays A B we wish to multiply each individual element in A by the corresponding element in B to do this we use the elementwise product. and elementwise power.ˆ. Nearly every time a command gives the error inner matrix dimensions do not agree it is because the elementwise product is required. Other fairly common operations are transpose and the colon operator :. The colon operator generates a vector of numbers, separated by some spacing. The default spacing is 1. For example the following command x=1:10; generates the vector [1,2,3,4,5,6,7,8,9,10]. To change the spacing we use x=1:2:10; which yields [1,3,5,7,9]. The spacing need not be integer. 2.4. Arrays and array slices. There are many ways we can generate arrays. We can generate random arrays, and special arrays using in-built commands. The useful ones are: zeros(n, M) an N M matrix of zeros, ones(n,m) an N M matrix of ones, eye(n) the N N identity, and rand(n,m) an N M matrix of random numbers distributed between 0 and 1. We can load the data in from a file using the loadfilename command. We can enter the arraymanually, separating row entries by spaces, and columns by semicolons. Eg: x=[1 2 3; 4 5 6; 7 8 9]; To reference parts of arrays we use the index of the entry or entries we are interested in. An entry in an array is indexed by the row i and the column j. The (i,j) entry of the array A is given by the command A(i,j). We can extract multiple entries of a array using the colon operator. For example the following code generates a 5 5 (random) array and extracts a 3 3 array from the middle. Subarrays are often called slices. N=5; array=rand(n,n); slice=array(2:4,2:4); The colon operator without arguments defaults to 1 :. Hence we can extract rows and columns in this way. To extract every second column of the array above we use slice2=array(1,1:2:5); 2.5. Editor. The Matlab editor has many useful built-in features. These are labeled in figure 2. Matlab ignores lines that start with a percentage sign %, and these lines are used to write comments in scripts and functions. If a line starts with two percentage characters %% then the Matlab editor interprets this starting a cell of code. Cells are blocks of code within a script which can be executed individually. This is useful for finding a mistake in your code, or for running small parts of a large program, when the whole program does not need to be run again. If there is an error in your code, and you are trying to identify the location of the error, a breakpoint will pause the execution of your code when Matlab reaches that line.

MATLAB SUMMARY FOR MATH2070/2970 3 Figure 2. 1. Save and run, 2. insert breakpoint, 3. Function menu, 4. Execute current cell, 5. Execute current cell and move to next cell, 6. Syntax highlighting, 7. Mulitple tabs. The function menu lets you search all built-in functions and shows the basic syntax of the function. The Matlab editor will run code, and put the output, including figures, directly into a pdf file. In the file menu there are two options: publish (or sometimes save and publish ) and publication configuration. In the publication configuration menu you may select from several output formats, including pdf, and html. 3. Plots In order to generate a plot we need arrays containing the values we wish to plot, and arrays containing the coordinates we wish to plot against. The coordinate arrays need only be one dimensional, even if the function we are plotting is two dimensional. The following block of code will generate a coordinate vector between 0 and L, discretised with N points N=100; L=2*pi; x=l*[0:n-1]/(n-1); 3.1. The plot command. To obtain a simple graph we use the plot command. Suppose we have generated x using the code above. We can plot sin(x) using plot(x,sin(x)); To obtain multiple plots on the same figure we can use the hold on command. All subsequent calls to the plot command will then a curve to the figure. To clear the figure (and turn off the hold) use the clf command. To create new figure windows we can use the command figure(n) where n is the integer which will be used to refer to the figure, eg figure(1). The plot command accepts many optional arguments to customise how the plot is displayed. We add a string containing the line style, colour, and marker information to our plot plot(x,sin(x), -ko ); This gives an unbroken line (the - command), in black (k), with a circle (o) marker on the plot. Note that the marker is optional and can be omitted. To obtain a plot with a dotted blue line

4 DUNCAN SUTHERLAND and diamond shapes we use :bd. The line styles are: - solid line (default), dashed line, : dotted line, -. dash-dot line. The some common markers are:. dot, o circle, asterisk, d diamond, s square. The colours are: r red, g green, b blue, k black, m magenta, c cyan, y yellow, w white. Combining any of these in the form of line, color, maker will give you the desired line. The commands xlabel and ylabel add text to the x-axis and y-axis. The title command adds a title to the figure. For example: plot(x,sin(x)+1); xlabel( Time spent looking at this graph ) ylabel( How much sense this graph makes ) title( A funny graph I stole from the internet ) 3.2. Legs. It is slightly tedious add a leg to a plot reliably. To do so we need the concept of a plot handle. Individual plots maybe assigned a name, called a handle, so that they can be referred to again later. For example the command plot01=plot(x,sin(x)); assigns the handle plot01. To make a leg, we need to label the data. Each plot has a property called DisplayName, which is the name displayed on the leg. By default the DisplayName is data n, where n is some integer. To modify the DisplayName we add the following to the plot command plot01=plot(x,sin(x), DisplayName, Sine Curve ); To display the leg use the leg command, and the plot handle plot01=plot(x,sin(x), DisplayName, Sine Curve ); leg([plot01]); For multiple leg entries, we just include the plot handles in the order they should appear: leg([entry01,entry02, etc]) 4. Other plot types To visualise three dimensional data we can plot the surface as a function of two coordinates, or we can plot the level curves of the surface as a function of coordinates. The inbuilt Matlab function peaks generates a sample function of two variables and some coordinates, we then plot this as a surface, and in a separate figure window, we plot the level curves. [x,y,z]=peaks; figure(1) mesh(x,y,z) title( Surface ) figure(2) contour(x,y,z) title( Level curves ) Note that z must be a two dimensional array. 5. Scripts and functions A script is a file containing a list of commands which Matlab executes sequentially. This is particularly useful for large calculations which require repetition. You will need to know how to write scripts to complete the tutorial exercises and the project. The script file may be written in the Matlab editor and executed with the play button. A function is similar to a script, but it accepts input arguments and returns a result. A function must be called from a script or from the command window, it cannot be executed directly.

MATLAB SUMMARY FOR MATH2070/2970 5 5.0.1. Simple scripts. Writing a script is straightforward. In the Matlab editor we simply type out the commands in order of execution. Here is an example script that generates a vector of coordinates, and plots some functions of those coordinates. %% Plotting sine and cosine % turn cell mode on clf %clear the figure N=100; %number of points used to discretise the interval L=2*pi; %length of the interval x=l*[0:n-1]/(n-1); %generates a vector between 0 and L, with N points plot(x,sin(x), r ) %plots a sine curve in red hold on %plot many things on the same graph plot(x,cos(x), b ) %plots a cosine curve in blue The difficulty is designing a script to solve a particular problem. Suppose we are given the task of plotting f(x) = sin(x)+ǫ where ǫ is a random variable distributed uniformly between 0.1 and 0.1, and x [0,2π]. We construct a plan for solving this problem. (1) Decide on the number of points used to discretise f(x) (2) Generate coordinates x between [0, 2π] (3) Generate a uniform random variable (4) Scale the random variable to the correct range (5) Make a vector containing the function f(x) (6) Plot f(x) vs. x The discretisation steps will need to be small to capture the small scale random perturbations. Initially we choose N = 100, if we find this is insufficient, we can edit the script and increase N. We can generate x with the following code: N=100; %number of points used to discretise the interval L=2*pi; %length of the interval %generates a vector between 0 and L, with N points x=l*[0:n-1]/(n-1); Next we have to generate the random perturbation ǫ. The inbuilt function rand(m, n) generates a random array, with m rows and n columns drawn from a uniformly distribution between 0 and 1. Note that our x coordinate vector has size (1,N). The following commands generate our ǫ vector %the -0.5 shifts our uniform distribution to -0.5 to 0.5 R=rand(1,N)-0.5; %the factor of 0.1/0.5 scales our random %variable to the required size epsilon=0.1*r/0.5; We can now construct our function f(x) and plot it fun=sin(x)+epsilon; plot(x,fun) If we run this script multiple times we should see a different plot each time, because the random variable ǫ is re-sampled each time the script is run. 5.0.2. Simple functions. Matlab functions are analogous to mathematical functions in that they have input arguments, which are mapped to a result. Many functions are built-in to Matlab. For example, sin(x), cos(x), etc. A Matlab function file always has the following form:

6 DUNCAN SUTHERLAND function result=function_name( list of input arguments ) commands which assign a value to the variable result The file name that the function is saved as should be the same as the function name. Matlab calls a function based on its filename. Here is a simple function, which returns the element-wise square of the input argument function y=square(x) y=x.^2 The first line declares the file to be a function, with result y, name square and input argument x. The second line takes x (which can be a vector or matrix) and squares every element in x and assigns that to y. Here is a more complicated example, which takes two input arguments and gives a single output, which is a two-dimensional Gaussian function. function z=gaussian(x,y) r=sqrt(x.^2+y.^2); z=exp(-r.^2); Functions can return multiple outputs by concatenating the outputs into a matrix. For example function [out1,out2]=two_outputs(x,y) out1=x-y; out2=x+y You will need to know how to write simple functions to complete the tutorial exercises. 6. Programing constructs The most difficult programing tasks required in this course involve using constructs such as the for-loop for repeated execution of code, and the if-then-else construct for conditional execution of code. The for-loop and the if statement are required for the project. 6.1. Repeated execution: for-loop. A for-loop is an iteration statement that allows a section of code to be repeatedly executed. A for loop has an explicit iterator, which starts at an initial value, and finishes at the final value. In Matlab the for-loop is implemented as follows for ITERATOR=START:END code to be repeated A for-loop can be used to evaluate the sum 10 n=1 n Sum=0; for n=1:10 %the iterator here is the variable n, %it starts at 1 and finishes at 10 Sum=Sum+n; Initially, Sum is zero, so the first iteration of the loop overwrites Sum with the value 0+1 = 1, the second iteration of the loop, Sum = 1 and is overwritten by 1 +2 = 3, etc. Sometimes the iterator is used to extract slices of an array: matrix=rand(10,10); %build a 10x10 random array for n=1:10 %the iterator here is the variable n, %it starts at 1 and finishes at 10 %take the mean of the nth column of matrix and store its %value in a new 1x10 array called meanval meanval(n)=mean(matrix(:,n));

MATLAB SUMMARY FOR MATH2070/2970 7 6.2. Conditional expressions: if-then-else. Conditional expressions perform different computations deping on the satisfaction of a specified condition. The specified condition is logical, that is, it must return a true or false result. The if statement is implemented in Matlab as follows if CONDITION 1 statements to execute if contition 1 is true elseif CONDITION 2 %an alternative condition statements to execute if contition 2 is true (and condition 1 is false) else statements to execute if contitions 1 and 2 are false An if-statement tests the conditions in sequential order. Hence in the previous example if both conditions 1 and 2 are true, the if statement will only execute the statements for condition 1. We can construct more complicated conditions using logical operations such as OR, denoted, AND denoted &&, etc. For example if CONDITION 1 statements to execute if contition 1 is true elseif CONDITION 2 %an alternative condition statements to execute if contition 2 is true (and condition 1 is false) elseif CONDITION 1 && CONDITION 2 %an alternative condition statements to execute if contitions 1 and 2 are true else statements to execute if contitions 1 and 2 are false Consider the Heaviside step function H(x), one particular definition is H(x) = 0 if x < 0, H(x) = 1 if x > 0, and H(x) = 1/2 if x = 0. To implement this in Matlab we need to be able to test if the value of x, is less than, greater than, or equal to zero. Note that in Matlab the single equals sign = assigns a value to a variable. For logical equality, the double equals sign == is used. function H=heaviside(x) if x>0 H=1; elseif x<0 H=0; elseif x==0 %note double equals H=1/2; Note this example does not work on a vector, as logical tests only work on scalars. To implement this function for vector inputs, we could use a for loop to test all elements sequentially.