NatSciLab - Numerical Software Introduction to MATLAB

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

Mechanical Engineering Department Second Year (2015)

PROGRAMMING WITH MATLAB WEEK 6

Classes 7-8 (4 hours). Graphics in Matlab.

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

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

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

The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development

MATLAB SUMMARY FOR MATH2070/2970

PART 1 PROGRAMMING WITH MATHLAB

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

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

Basic Graphs. Dmitry Adamskiy 16 November 2011

MATLAB Introduction to MATLAB Programming

1. Register an account on: using your Oxford address

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

INTERNATIONAL EDITION. MATLAB for Engineers. Third Edition. Holly Moore

INC151 Electrical Engineering Software Practice. MATLAB Graphics. Dr.Wanchak Lenwari :Control System and Instrumentation Engineering, KMUTT 1

3D plot of a surface in Matlab

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

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

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

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

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

MATLAB Functions and Graphics

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

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

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

Programming 1. Script files. help cd Example:

Introduction to Programming in MATLAB

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Graphics Example a final product:

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

What is MATLAB? It is a high-level programming language. for numerical computations for symbolic computations for scientific visualizations

2D LINE PLOTS... 1 The plot() Command... 1 Labeling and Annotating Figures... 5 The subplot() Command... 7 The polarplot() Command...

Overview. Lecture 13: Graphics and Visualisation. Graphics & Visualisation 2D plotting. Graphics and visualisation of data in Matlab

Graphics in MATLAB. Responsible teacher: Anatoliy Malyarenko. November 10, Abstract. Basic Plotting Commands

Dr. Iyad Jafar. Adapted from the publisher slides

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

Computer Programming in MATLAB

Lab of COMP 406 Introduction of Matlab (II) Graphics and Visualization

MAT 275 Laboratory 1 Introduction to MATLAB

Purpose of the lecture MATLAB MATLAB

Introduction to MATLAB

Plotting - Practice session

W1005 Intro to CS and Programming in MATLAB. Plo9ng & Visualiza?on. Fall 2014 Instructor: Ilia Vovsha. hgp://

Getting Started with Matlab

More on Plots. Dmitry Adamskiy 30 Nov 2011

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

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

Computing Fundamentals Plotting

Introduction to MATLAB: Graphics

Introduction to MATLAB LAB 1

Introduction to Matlab

Getting Started with MATLAB

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

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

1 Introduction to Matlab

CSE 123. Plots in MATLAB

Dr Richard Greenaway

AMS 27L LAB #2 Winter 2009

Introduction to Simulink

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

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Introduction to MatLab. Introduction to MatLab K. Craig 1

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

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

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.

Programming in Mathematics. Mili I. Shah

Introduction to MATLAB

MATLAB Guide to Fibonacci Numbers

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

Math 7 Elementary Linear Algebra PLOTS and ROTATIONS

FF505/FY505 Computational Science. MATLAB Graphics. Marco Chiarandini

Quick MATLAB Syntax Guide

Introduction to MATLAB

Laboratory 1 Octave Tutorial

Introduction to PartSim and Matlab

Additional Plot Types and Plot Formatting

DATA PLOTTING WITH MATLAB

Chapter 1 Introduction to MATLAB

GRAPHICS AND VISUALISATION WITH MATLAB

Introduction to MATLAB Practical 1

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

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

Lecture 3 for Math 398 Section 952: Graphics in Matlab

Introduction to Matlab for Engineers

Part #6. A0B17MTB Matlab. Miloslav Čapek Filip Kozák, Viktor Adler, Pavel Valtr

MATH 2221A Mathematics Laboratory II

MATLAB Laboratory 09/23/10 Lecture. Chapters 5 and 9: Plotting

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

Introduction to Matlab

Graphics and plotting techniques

1 >> Lecture 4 2 >> 3 >> -- Graphics 4 >> Zheng-Liang Lu 184 / 243

EL2310 Scientific Programming

INTRODUCTION TO NUMERICAL ANALYSIS

LabVIEW MathScript Quick Reference

User Defined Functions

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

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

Transcription:

Outline 110112 NatSciLab - Numerical Software Introduction to MATLAB Onur Oktay Jacobs University Bremen Spring 2010

Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization

Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization

.m files An m-file is a plain text file that contains MATLAB commands, with the filename extension.m. There are 2 types of m-files, scripts and functions. You can start an m-file by typing >> edit filename An m-file should be saved in the current directory or in the path in order to be executed. The path is just a list of directories in which MATLAB will look for files. Use editpath command to see and change the path. There is no need to compile m-files.

Script.m files The contents of a script m-file are literally interpreted as if they were typed at the prompt. If you want to repeat a group of lines various times, it is more convenient to write and save those lines in a script than using the prompt. Type >> run filename at the command line to run the script filename.m Some good reasons to use scripts are - Revising a group of more than four or five lines. - Reproducing your work at a later time. - Running a CPU-intensive job in the background.

Function.m files Function m-files are used to write and store often complicated numerical functions. Each function starts with a line such as function [out1,out2] = myfun(in1,in2,in3) The variables in1, in2, in3 are input arguments, and out1, out2 are output arguments. You can have as many input and output arguments as you like. Most of the functions built into MATLAB (except core math functions) are themselves m-files, which you can read and copy.

Function.m files A simple example of a function m-file: quadformula.m function [x1,x2] = quadformula(a,b,c) d = sqrt(bˆ2-4 a c); x1 = (- b + d) / (2 a); x2 = (- b - d) / (2 a); On the prompt, type >> [r1,r2] = quadformula(1,-2,1) r1 = 1 r2 = 1

Function.m files - Subfunctions A single m-file may hold more than one function definition. The function header at the first line of an m-file defines the primary function. All others are subfunctions. function [x1,x2] = quadformula(a,b,c) % primary function d = discrim(a,b,c); x1 = (-b + d) / (2*a); x2 = (-b - d) / (2*a); end function D = discrim(a,b,c) % subfunction D = sqrt(bˆ2-4*a*c); end

Function.m files - defaults nargin: Number of input arguments. Set default values for the inputs that are not provided. nargout: Number of output arguments. Set default action if one or more outputs are not called. An example: sincab.m function y = sincab(t,a,b) if nargin< 2; a=1; end % default value a=1 if nargin< 3; b=2; end % default value b=2 y = sin(t.ˆa)./(t.ˆb); if nargout==0; % default action: plot if no output is called figure; plot(t,y); end end

Script or Function? Functions have their own local workspace. Scripts use the main workspace. Function Script Q1 No Yes Q2 No Yes Q1: Are the variables in the main workspace visible? Q2: When executed, do the variables created appear in the main workspace? Functions are faster than scripts. - Functions are compiled into memory when executed for the first time. Subsequent invocations skip this interpretation step. - No matter how many times you execute the same script, MATLAB must spend time parsing your syntax. Functions require all inputs and outputs to be stated. Use scripts for attention-free execution.

Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization

if/else structure if (condition 1 true) statement 1 elseif (condition 2 true) statement 2 elseif (condition 3 true) statement 3. else default statement end

factorialscript.m Example if isreal(x) % if x is not real error ( x cannot be a complex number ); elseif (x < 0) error ( x cannot be a negative number ); elseif (x > 1000) error( x is too large ); elseif (x > 0) & (x = round(x)) % if x is not equal to round(x) disp( decimal part of x will be ignored ); factorial = prod(1:x); else factorial = prod(1:x); end

switch/case structure switch variable case value1 statement 1 case value2 statement 2 case value3 statement 3. otherwise default statement end equivalent to if variable == value1; statement 1 elseif variable == value2; statement 2 elseif variable == value3; statement 3. else default statement end Note: Unlike the C language switch statement, the MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute.

switch/case switch mod(x,6) case 0 xnew = x/6; case {1, 5} xnew = xˆ2-1; case 4 xnew = x/2; otherwise xnew = xˆ2 + 2; end if (mod(x,6)==0) xnew = x/6; elseif (mod(x,6)==1) (mod(x,6)==5) xnew = xˆ2-1; elseif (mod(x,6)==4) xnew = x/2; else xnew = xˆ2 + 2; end

Loops: for & while structure for var = vector statement end Use if it is necessary to repeat the statement a fixed number of times. Example: find sum of all prime numbers < 100 x = 1:100; s = 0; for k = 1:100; s = s + x(k)*isprime(x(k)); end structure while (condition true) statement end Use if it is necessary to repeat the statement based on a condition. Example: find sum of all prime numbers < 100 x = 1; s = 0; while (x < 100) s = s + x * isprime(x); x=x+1; end

Loops: for & while Its a good idea to limit the number of repetitions to avoid infinite loops. Use for loops rather than while loops. Maxiter = 100; % Number of repetitions for n = 1:Maxiter x = pi sin(x); end Use break. A break immediately ends the loop, and jumps to the first line after the loop. n = 0; Maxiter = 100; % Number of repetitions while (err > 0.01) err = abs(pi sin(x) - x); x = pi sin(x); n = n+1; % loop counter if n>maxiter, break, end end

Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization

Anonymous functions We can quickly form functions at the command line. For example, let f(x) = 2e x x 2 cos(x) + 5x log(x) Usage g(x, y, z) = e xy/z y sin(z)/x + log(z). fhandle = @(argument list)(expression) >> f = @(x)( 2*exp(x) (x.ˆ2).*cos(x) + 5*x.*log(x) ); >> g = @(x,y,z)( exp(x.*y)./z y.*sin(z)./ x + log(z) ); Alternatively, we can use inline >> f = inline( 2*exp(x) (x.ˆ2).*cos(x) + 5*x.*log(x), x ); >> g = inline( exp(x.*y)./z y.*sin(z)./ x + log(z), x, y, z ); Make your functions array-smart by inserting a dot before *, /,ˆ

Anonymous functions We cannot add or multiply anonymous functions. >> f+f returns an error message. x is a numerical array f(x) is a numerical array. We can, for example >> x = ones(2,3); y = rand(2,3); >> sumfxfy = f(x)+f(y); prodfxfy = f(x).*f(y); We can form anonymous functions with outside parameters >> h = @(x)( a*cos(x) + b*sin(x)); >> h(2) returns an error message if a and b are not defined. >> a=0.3; b=0.5; h(2) Multiple anonymous functions can be used together. For example, if π F(x, t) = e u2 /t sin(x u)du, 0 we can >> F = @(x,t)( quad( @(u)(exp(-(u.ˆ2)./t).*sin(x-u)),0,pi) );

Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization

Some Graphing Commands Curve graphing commands plot ezplot: plot for anonymous functions. plot3: plot curves in 3D space. Surface graphing commands surf, mesh: surface graphing in 3D. ezsurf, ezmesh: surface graphing for anonymous functions. colorbar, colormap: show/change color scaling. pcolor: top view of a colored surface. contour, ezcontour: contour plot of surfaces Figure properties and annotation figure: open a new empty figure window. hold on, hold off, grid on, grid off subplot: multiple graphs in one figure. axis, xlim, ylim: axis limits. title, xlabel, ylabel: graph and axis labels. legend: display/edit the legend for graphs with multiple curves.

plot plot uses line segments to connect points given by two vectors of the same length. Usage plot(x,y, color-style-marker ) x is a vector of length N, which keeps the x-coordinates. y is a vector of length N, which keeps the y-coordinates. color-style-marker [OPTIONAL] is a string that gives the color, style, marker type of the plot. Default value is b, if not provided. if x & y doesn t have the same length, plot(x,y) causes an error message. y can be a r N array. In this case, plot(x,y) plots each row of y versus x. x must always be a vector.

plot Here is a simple example. >> t = pi*(0:0.02:2); >> plot(t,sin(t)) Suppose you want to put a marker at each data point. >> plot(t,sin(t), o ) Also draw a cosine curve, make it red to distinguish. >> plot(t,cos(t), r ) The sine curve is erased. hold on to keep the previously drawn graphs. >> plot(t,sin(t), o ) >> hold on >> plot(t,cos(t), r ) >> hold off You can plot multiple curves at once: >> figure % forms a new empty figure >> plot(t, [t; t.ˆ2; t.ˆ3] ) MATLAB automatically assigns different colors to the curves.

plot - color, line style, marker Type Values Meanings Values Meanings Color c cyan g green m magenta b blue y yellow w white r red k black Line - solid : dotted style dashed.- dash-dot Marker + plus mark ˆ filled upward triangle type o unfilled circle v filled downward triangle * asterisk > filled right-pointing triangle x letter x < filled left-pointing triangle s filled square p filled pentagram d filled diamond h filled hexagram

ezplot For anonymous functions, we use ezplot. Usage ezplot(f, [xmin xmax]) f is an anonymous function handle. xmin, xmax [OPTIONAL] are x-axis boundaries of the graph. % plots f=f(x) on the given interval % if f=f(x,y) of 2 variables, plots the curve given by f(x, y) = 0. ezplot(x,y, [tmin,tmax]) x,y are anonymous functions of a single common variable t. tmin, tmax [OPTIONAL] are the limits of t. % plots the parametric curve x=x(t), y=y(t) for t [tmin,tmax] For example, >> f = @(x)( exp(3*sin(x)-cos(2*x)) ); >> ezplot(f, [0 4] ) % plots of f on [0,4]. >> g = @(x,y)(x.ˆ4 + y.ˆ4-1); >> ezplot( g, [-1 1] ) % plots the contour g(x, y) = 0 on [-1,1].

subplot We use subplot to form a single figure with multiple graphs. Usage subplot(m,n,k) m: number of rows in the figure. n: number of columns in the figure. k: position of the graph in the figure. Counting is done from left right, top bottom. For instance, subplot(3,4,1) subplot(3,4,2) subplot(3,4,3) subplot(3,4,4) subplot(3,4,5) subplot(3,4,6) subplot(3,4,7) subplot(3,4,8) subplot(3,4,9) subplot(3,4,10) subplot(3,4,11) subplot(3,4,12)

subplot and annotation Example: >> t = pi*(0:0.02:2); f = t.*sin(t); >> f1= @(x)( sin(x) + x.*cos(x) ); >> subplot(2,2,1) % start working on the 1st cell in the figure >> plot(t,f) >> axis( [0 2*pi -5 2] ) % set axis limits >> title( Graph of f(t) = t sin(t) ); % sets a title to the graph >> xlabel( time ); ylabel( velocity ); % label the axes >> >> subplot(2,2,3) % start working on the 3rd cell in the figure >> ezplot(f1,[0 2*pi]) >> xlabel( time ); ylabel( acceleration ); >> subplot(2,2,[2,4]) % merge 2nd & 4th cells >> plot3(cos(t),sin(t),sin(3*t))

surf, mesh surf (mesh) forms a 3D shaded surface (wireframed mesh) from a matrix of z-coordinates by linear interpolation. Usage surf(x,y,z) Z is a matrix defining the z-coordinates of a surface. X,Y [OPTIONAL] are matrices defining the x,y-coordinates. mesh has the same usage. X & Y can be vectors, length(x) = n and length(y) = m, where [m,n] = size(z). the vertices of the surface faces are (X(j), Y(i), Z(i,j)) triples. To form X & Y matrices for arbitrary domains, use meshgrid

ezsurf, ezmesh For anonymous functions, use ezsurf (ezmesh) Usage ezsurf(f, [xmin xmax ymin ymax]) f is an anonymous function handle. xmin, xmax, ymin, ymax [OPTIONAL] are boundaries of the xy-plane. Default values xmin = ymin = -2*pi, xmax = ymax = 2*pi, if not entered % plots f=f(x,y) on the given interval ezsurf(x,y,z, [tmin,tmax,smin,smax]) x,y,z are anonymous functions of two common variables t,s. tmin, tmax, smin, smax [OPTIONAL] are the limits of t,s. Default values tmin = smin = -2*pi, tmax = smax = 2*pi, if not entered % plots the parametric surface x = x(s,t), y = y(s,t), z = z(s,t) for t [tmin,tmax], s [smin,smax] ezmesh has the same usage.

Example >> figure; ezsurf (@(x,y)sin(x.ˆ2+y), [0 pi 0 2*pi] ) >> f = @(x,y)( sin(x.ˆ2+y) ); >> x = pi*(0:0.02:1); y = 2*x; >> [X,Y] = meshgrid(x,y); % form a grid of points in the xy-plane >> Z = f(x,y); >> figure; surf(x,y,z) >> colorbar % display the colorbar in the figure >> colormap gray % change the color scaling The coloring is determined by shading in between the data points: >> shading flat >> shading interp

surf - shading flat shading: each face/ mesh line has constant color determined by one boundary point. interpolated shading: the color is determined by interpolation of the boundary values. It makes smoother pictures, but can be very slow to render, particularly on printers. faceted shading: uses flat shading for the faces and black for the edges.

Outline 1.m files 2 Programming Branching (if, switch) Loops (for, while) 3 Anonymous functions 4 Basic Graphing Curve plotting (plot,plot3,contour) Surface plotting (surf, mesh) 5 Efficient coding - Vectorization

How to make your code run faster: Vectorization: Rewrite loops by indexing and matrix operations. Because Matlab is optimized for matrix operations. Matlab s core strength is the efficient handling of vector and matrix operations. Loops slow down Matlab. Pre-allocate memory hhen forming large arrays/matrices. For example, use zeros to make a matrix of the desired size. Because, repeatedly resizing arrays requires that MATLAB spend extra time looking for larger contiguous blocks of memory and then moving the array into those blocks. Use built-in functions. Use functions rather than scripts. Because, a function is parsed into the memory at the first time it is executed/modified. A script is parsed one line at a time, each time it is executed. Parsing/interpretation require extra time.

Vectorization - Indexing Example: x is a vector and we want to compute a matrix D = [d ij ] such that d ij = e x i sin x j. The standard programming involves two nested loops. >> n = length(x); >> D = zeros(n); % preallocate memory for D >> for j = 1:n >> for i = 1:n >> D(i,j) = exp(x(i))*sin(x(j)); >> end >> end We can vectorize as follows. >> n = length(x); >> ind = ones(n,1)*(1:n); % forms an nxn index matrix. >> X = x(ind); >> D = exp(x).*sin(x. );

Vectorization - Index Masks Example: A is a numerical array/matrix. We want to set A ij = 0 if A ij < 0.05 The standard programming involves two nested loops. >> [m n] = size(a); >> for j=1:m >> for k=1:n >> if abs(a(j,k))<0.05, A(j,k)=0, end >> end >> end We can vectorize as follows. >> mask = (abs(a)>=0.05); % form a logical index mask >> A = A.*mask;

Recommended Reading Scientific Computing with MATLAB and Octave by Quarteroni & Saleri, Chapter 3, Sections 3.1 and 3.4.