CSE/Math 456 and CSE/Math 550 Matlab Tutorial and Demo

Similar documents
CSE/Math 485 Matlab Tutorial and Demo

A Brief Introduction to MATLAB

Grace days can not be used for this assignment

1 Introduction to Matlab

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

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

A Guide to Using Some Basic MATLAB Functions

MATLAB Lecture 1. Introduction to MATLAB

MATLAB GUIDE UMD PHYS401 SPRING 2012

A very brief Matlab introduction

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

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

Introduction to Matlab

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

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Introduction to MATLAB

MATH 5520 Basics of MATLAB

MATH 3511 Basics of MATLAB

Dr Richard Greenaway

Matlab Introduction. Scalar Variables and Arithmetic Operators

Matlab Tutorial and Exercises for COMP61021

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

What is MATLAB and howtostart it up?

Mathematics 4330/5344 #1 Matlab and Numerical Approximation

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

Introduction to Matlab

Stokes Modelling Workshop

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

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

MATLAB Premier. Middle East Technical University Department of Mechanical Engineering ME 304 1/50

Teaching Manual Math 2131

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

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

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

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

A QUICK INTRODUCTION TO MATLAB

Some elements for Matlab programming

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Introduction to MATLAB

How to learn MATLAB? Some predefined variables

University of Alberta

Getting Started with MATLAB

Math 2250 MATLAB TUTORIAL Fall 2005

Starting MATLAB To logon onto a Temple workstation at the Tech Center, follow the directions below.

Introduction to MATLAB for CSE390

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

Math Scientific Computing - Matlab Intro and Exercises: Spring 2003

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

Introduction to MATLAB Practical 1

LAB 1 General MATLAB Information 1

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

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

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

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Introduction to MATLAB

Introduction to Matlab

A quick Matlab tutorial

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.

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

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

An Introductory Guide to MATLAB

Introduction to MATLAB

CSCI 6906: Fundamentals of Computational Neuroimaging. Thomas P. Trappenberg Dalhousie University

MATLAB Premier. Asst. Prof. Dr. Melik DÖLEN. Middle East Technical University Department of Mechanical Engineering 10/30/04 ME 304 1

Matlab Tutorial for COMP24111 (includes exercise 1)

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

Lecturer: Keyvan Dehmamy

Introduction to Matlab

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

MAT 275 Laboratory 1 Introduction to MATLAB

Matlab and Octave: Quick Introduction and Examples 1 Basics

Introduction to Unix and Matlab

MATLAB BEGINNER S GUIDE

SF1901 Probability Theory and Statistics: Autumn 2016 Lab 0 for TCOMK

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

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

EE 301 Lab 1 Introduction to MATLAB

Lecture 2: Variables, Vectors and Matrices in MATLAB

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

MATLAB Introductory Course Computer Exercise Session

Matlab Tutorial: Basics

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

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction to Matlab

Introduction to MATLAB

16.06/16.07 Matlab/Simulink Tutorial

Getting Started with MATLAB

MATLAB QUICK START TUTORIAL

Matlab Tutorial, CDS

Introduction to MATLAB LAB 1

Introduction to GNU-Octave

1 Overview of the standard Matlab syntax

LAB 2: Linear Equations and Matrix Algebra. Preliminaries

MATLAB Tutorial Matrices & Vectors MATRICES AND VECTORS

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

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

ME305: Introduction to System Dynamics

Introduction to MATLAB

Matlab course at. P. Ciuciu 1,2. 1: CEA/NeuroSpin/LNAO 2: IFR49

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

Transcription:

CSE/Math 456 and CSE/Math 550 Matlab Tutorial and Demo MATLAB is very powerful and varied software package for scientific computing. It is based upon matrices and m files. It is invoked by typing % matlab I recommend the creation of a directory called matlab. Use the two commands % mkdir matlab (done only once) % cd matlab before invoking matlab. Put all.m file in this directory. Matrices are the main data element. They can be introduced in the following four ways. 1. As an explicit list of elements. 2. Generated by built in statements or functions. 3. Created by m files. 4. Loaded from external data files. For instance consider the MATLAB command A = [ 1 2 3 ; 4 5 6 ; 7 8 9] It immediately outputs A = 1 2 3 4 5 6 7 8 9 (no parentheses or brackets). Or if you create a file called gena.m and type A = [ 1 2 3 ; 4 5 6 ; 7 8 9] in that file. Then type gena it will also produce A exactly as above. The line 1

gena; will also produce A, but will not print it on the screen. It is important to remember the distinction between row and column vectors in MATLAB. If you type x = [-1.3 sqrt(3) (1+2+3)*4/5] you get Row vectors are default. On the other hand, if you type x = [-1.3; sqrt(3); (1+2+3)*4/5] you get x = 1.3 1.7321 4.8000 x = 1.3 1.7321 4.8000. The most important MATLAB command is help. help This lists all help topics help inv Gives the help information for the function inv for inverting a matrix. help help Explains the help command. MATLAB m files contain two types of items 1. scripts 2. user defined functions The gena.m file described above is an example of a script. It just lines of text consisting of MATLAB commands. Invoking the script (done when typing gena or the name of the script file without the.m ) is equivalent to typing the commands directly into MATLAB. Functions have function statements as their first line. Two examples are function A=fun1(x,y,z) 2

function [A,B,C]=fun2(x,y,z) These should be placed in files called fun1.m and fun2.m respectively. Here x,y,z are input arguments, and A,B,C are output arguments. Any of these can be simple variables, vectors, or matrices. For examples of functions look at the files cosx.m and bisect2.m on the class web page. MATLAB supports the usual programming structures if, for, while and switch. The syntax is a bit different from C syntax, but the use is much the same. The function bisect2.m contains if and while statements. The following for statement sums the first n integers. sum=0; for k=1:n sum=sum+k; end; Two useful MATLAB command are save and load. MATLAB creates a workspace for all of your variables. When you are done with a MATLAB session, you type quit and you are out of MATLAB. However, your workspace and all of the variables that you are using vanish, they will not be there when you log on to MATLAB again. If, before you quit, you type save mysession the workspace will be saved in the file mysession.mat. If you type save mysession X Y Z then only the variables X,Y, and Z will be saved. save is a completelydestructive operation, mysession.mat is completely overwritten. If you want to retreive your workspace from the previous session type load mysession To know what variables you have type who Most matrix operations in MATLAB are one line. The matrix transpose operation is 3

B = A ; Thus if A has the contents then B will have the contents A = B = 1 2 3 4 5 6 7 8 0 1 4 7 2 5 8 3 6 0 Here are some other functions C = A+B just adds A and B. C = A*B just multplies A and B. C = X *Y does the operation C = X T Y. b = A*x is a matrix vector multiply. If the dimensions are wrong in any of these operations, you will get an error message. There are two important functions associated with matrices, size and length. The statement [m,n]=size(a) returns the dimensions of the array A. If m = 1, A is just a row vector, if n = 1 then A is column vector, and if m = n = 1, then A is scalar. The statement p=length(a) returns the larger of the two outputs of size. There are a number of ways to generate special vectors and matrices. Here are some examples x = 1:5 yields y = 0:pi/4:pi x = 1 2 3 4 5. 4

yields y = 0 π/4 π/2 3π/4 π. z = 6:-1:1 yields z = 6 5 4 3 2 1. The statement y =exp(z) yields y = e 6 e 5 e 4 e 3 e 2 e 1. Actually, it produces the appropriate floating point numbers. exp is exponential function. In fact, you can also type A=randn(5,5); Y=exp(A); Of course, This yields the exponential matrix, which is the solution to the ordinary differential system Y (t) = AY (t) Y (0) = I at t = 1. MATLAB supports lots of math functions, such as exp, log, log10, sin, cos, tan, asin, atan, and some you have probably never heard of. Where it makes sense, it supports matrix versions of them as well. Functions can also be defined inline. An example is f= inline( 1/(x+1) ) They can be passed as arguments in other functions in two ways. The first is through the use of function handles. Let s say we want to compute diff(f, x, h) = [f(x + h/2) f(x h/2)]/h the centered difference approximation to the first derivative. If we have the function fun1 defined either in an m-file or inline, we call diff by 5

yprime=diff(fun1,x,h) where fun1 is called a function handle. The m-file for diff could look like this. function yprime=diff(f,x,h) yprime=(feval(f,x+h/2)-feval(f,x-h/2))/h; Alternative, this can be done with strings. If your version of MATLAB is older than version 6, you have to do it this way. Octave does it similarly, but with slightly different syntax. yprime=diff( fun1,x,h); function yprime=diff(f,x,h) yprime=(eval([f, (x+h/2) ])-eval([f, (x-h/2) ])/h; The MATLAB Demo First, log on to your account in 222 IST. If you are unable to do that, please get hold of me. Try to bring up a terminal window. Before doing MATLAB, you need to create a.forward file. Thus use emacs or vi or your favorite UNIX, open a file in the main directory and type one line, an email address, e.g. alan.turing@mymachine.edu and then save the file. Any email I send you for this class will go directly to that address. On your next UNIX prompt type % mkdir matlab (or whatever you wish to name this directory) % cd matlab Then type % matlab You should get a brief graphic display and then the prompt the command A = randn(5,5) This generates a random 5 5 matrix according to the normal distribution. Open a second X-window and also type % cd matlab You will use this second X window to download and use m-files. In the matlab window type [U,S,V]=svd(A) Ainv=V*inv(S)*U 6

I= eye(5,5) What do svd, inv,eye do? Use the help command if this is not obvious. Compute R= I-Ainv*A Is the answer what you expected? Now type B=ones(5,5) and type inv(b) help sum Use the sum function to sum all of the elements in A. ii=[1 4 5] jj=[2 3 5] C=A(ii,jj) What did you just do? Do you now see how MATLAB indexes arrays? What is A(:, 1: 3), A(2: 4, : ) and A(2: 4, 1: 3)? Notice MATLAB automatically prints the results of any computation on the screen. Under some circumstances, that is not a good idea. If we type ii=[1 4 5]; jj=[2 3 5]; C=A(ii,jj); then MATLAB does its work silently. C But everything is still there. to display the answer. Now a brief introduction to plotting. inc=pi/25 x=0:inc:2*pi y=sin(x) plot(x,y) 7

To label the graph type title( Plot of sin x for one period ) xlabel( Domain From zero to 2*pi ) ylabel( Range From -1 to 1 ) You can print the plot clicking on File and then on Print and then click on Print. DO NOT DO THIS NOW. For now, click Cancel. Print it at your convenience some other time. If you click on Save As.. in the file menu, you can save the graph as.ps (PostScript) file which can be viewed with ghostview. Click on Netscape. Go to http://www.cse.psu.edu/ barlow/cse550/kahan.m. You are now to download this into your matlab directory. To do that, click File and the Save As... It should give you a list of your directories, click matlab. Repeat the procedure for http://www.cse.psu.edu/ barlow/cse550/hilbert.m. These are m-files from my personal stash. The first one, kahan.m, generates a benign looking upper triangular matrix that is actually ill-conditioned. The second, hilbert.m, generates more obviously ill-conditioned matrix. For both matrices, their condition number increases exponentially with n. diary n=50 c=0.3 A=kahan(50,0.30); [X,Lambda]=eig(A); [U,S,V]=svd(A); S(50,50)-abs(Lambda(50,50)) diary off In your other window, look in your diary file. the function eig computes the eigenvalues and eigenvectors of A. The function svd computes the singular value decomposition. Now compute diary X=hilbert(40); H=X *X; s=svd(x); lambda=eig(h); 8

Did you get negative eigenvalues? X is nonsingular (though not to machine precision), theoretically H should be positive definite (and have all positive eigenvalues). Here is simple least squares computation in MATLAB. Y=randn(10,7); [QY,RY]=qr(Y,0); X=QY*hilbert(7); [Q,R]=qr(X); rexact=1e-3*q(:,8:10)*[1;2;3]; yexact=ones(7,1); b=x*yexact+rexact; c=q *b; y=r(1:7,1:7)\c(1:7) r=q(:,8:10)*c(8:10) r1=b-x*y norm(y-yexact) norm(r-rexact) norm(r1-rexact) Did you get reasonable answers? CSE/Math 456 students, did you see how I contrived the example to obtain a particular solution and residual? CSE/Math 550 students, you might be able to figure this out, but I have not explicitly taught you this yet. So far, I have given a small portion of MATLAB. Throughout the semester, I will give you more pieces of it. MATLAB is set up so that a computer literate person can learn much on his/her own. MATLAB has many toolboxes including ones for image processing, signal processing, splines, symbolic computing, and partial differential equations. To learn about them type tutdemo I encourage you to have some fun with these, MATLAB can be very playful. The matrix functions are a little too good for this course, because what I want to teach you is inside of them; invisible to the user. 9