Contents. MATLAB Tutorial. Contents. General Functions. What is MATLAB? Calculations at the Command Line

Similar documents
Introduction to Matlab

Financial Econometrics MFE MATLAB Introduction. Kevin Sheppard University of Oxford

MATLAB Functions. function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m)

MATLAB Basics MATLAB numbers and numeric formats

Introduction. Chapter 1

u = [ 2 4 5] has one row with three components (a 3 v = [2 4 5] has three rows separated by semicolons (a 3 w = 2:5 generates the row vector w = [ 2 3

Basic Concepts in Matlab

Introductory Course to Matlab with Financial Case Studies

Einführung in MATLAB Sommer Campus 2004

CD-ROM Appendix E: Matlab

Appendix: Tutorial Introduction to MATLAB

Introduction to MATLAB (Basics) Reference from: Azernikov Sergei

MATLAB LECTURE NOTES. Dr. ADİL YÜCEL. Istanbul Technical University Department of Mechanical Engineering

Engineering Problem Solving and Excel. EGN 1006 Introduction to Engineering

2+2 Just type and press enter and the answer comes up ans = 4

How long is the vector? >> length(x) >> d=size(x) % What are the entries in the matrix d?

How To Use Matlab

MATLAB Tutorial. Chapter 6. Writing and calling functions

PGR Computing Programming Skills

(!' ) "' # "*# "!(!' +,

Beginner s Matlab Tutorial

MATLAB DFS. Interface Library. User Guide

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

Part VI. Scientific Computing in Python

Beginning Matlab Exercises

Simple Programming in MATLAB. Plotting a graph using MATLAB involves three steps:

MATLAB Programming. Problem 1: Sequential

Introduction to Matlab: Application to Electrical Engineering

SOME EXCEL FORMULAS AND FUNCTIONS

Signal Processing First Lab 01: Introduction to MATLAB. 3. Learn a little about advanced programming techniques for MATLAB, i.e., vectorization.

Analysis of System Performance IN2072 Chapter M Matlab Tutorial

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

FIRST STEPS WITH SCILAB

5: Magnitude 6: Convert to Polar 7: Convert to Rectangular

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

Tutorial Program. 1. Basics

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

Linear Algebra and TI 89

A few useful MATLAB functions

MATLAB Primer. R2015b

Programming Exercise 3: Multi-class Classification and Neural Networks

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

Programming in MATLAB

Introduction to Computing I - MATLAB

MATRIX ALGEBRA AND SYSTEMS OF EQUATIONS. + + x 2. x n. a 11 a 12 a 1n b 1 a 21 a 22 a 2n b 2 a 31 a 32 a 3n b 3. a m1 a m2 a mn b m

Notes on Determinant

Linear Algebra Review. Vectors

Quick Tour of Mathcad and Examples

MATH 423 Linear Algebra II Lecture 38: Generalized eigenvectors. Jordan canonical form (continued).

Eigenvalues, Eigenvectors, Matrix Factoring, and Principal Components

Data Tool Platform SQL Development Tools

Simply Accounting Intelligence Tips and Tricks Booklet Vol. 1

Computational Mathematics with Python

PTC Mathcad Prime 3.0 Keyboard Shortcuts

MATLAB MANUAL AND INTRODUCTORY TUTORIALS

MATRIX ALGEBRA AND SYSTEMS OF EQUATIONS

MatLab Basics. Now, press return to see what Matlab has stored as your variable x. You should see:

(!' ) "' # "*# "!(!' +,

AIMMS Function Reference - Arithmetic Functions

Introduction to Numerical Math and Matlab Programming

The Language of Technical Computing. Computation. Visualization. Programming. MATLAB Programming Tips Version 6

13 MATH FACTS a = The elements of a vector have a graphical interpretation, which is particularly easy to see in two or three dimensions.

Computational Mathematics with Python

Summary: Transformations. Lecture 14 Parameter Estimation Readings T&V Sec Parameter Estimation: Fitting Geometric Models

Computational Mathematics with Python

Chapter 5 Functions. Introducing Functions

MATLAB Primer. R2015a

INTRODUCTION TO EXCEL

Introduction to MATLAB

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

Review Jeopardy. Blue vs. Orange. Review Jeopardy

PLOTTING IN SCILAB.

Similarity and Diagonalization. Similar Matrices

Using Casio Graphics Calculators

MS-EXCEL: ANALYSIS OF EXPERIMENTAL DATA

COMSOL. Script USER S GUIDE V ERSION 1.1

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

Vector and Matrix Norms

R: A self-learn tutorial

Mathematica Tutorial

Tips and Tricks SAGE ACCPAC INTELLIGENCE

Data Mining: Algorithms and Applications Matrix Math Review

Orthogonal Diagonalization of Symmetric Matrices

Chapter One Introduction to Programming

8 Square matrices continued: Determinants

MATLAB Workshop 3 - Vectors in MATLAB

Access Queries (Office 2003)

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

ERDAS Spatial Modeler Language Reference Manual

Introduction to Matrix Algebra

an interactive introduction to MATLAB

Introduction to Matrices for Engineers

MATLAB. The Language of Technical Computing. Programming Tips Version 7

GUI Input and Output. Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University

Matrix Indexing in MATLAB

Similar matrices and Jordan form

MATLAB. Input and Output

A Short Guide to R with RStudio

Transcription:

Contents MATLAB Tutorial Based on IPLab@SUT Matlab Tutorial What Matlab? Matrices Numerical Arrays String Arrays Elementary Math Logical Operators Math Functions Importing and Exporting Data 2 Contents Graphics Fundamentals 2D plotting Subplots 3D plotting Editing and Debugging M-files Script and Function Files Basic Parts of an M-file Flow Control Statements M-file Programming Data Types Continued What MATLAB? high-performance software Computation Vualization Easy-to-use environment. high-level language Data types Functions Control flow statements Input/output Graphics Object-oriented programming capabilities 3 5 Calculations at the Command Line General Functions 9 MATLAB as a calculator Assigning Variables» -5/(4.8+5.32)^2 ans» a 2; ans 2; -.488» b 5; -.488 5;» (3+4i)*(3-4i)» a^b a^b ans ans ans ans 25 25 32 32» cos(pi/2)» x 5/2*pi; 5/2*pi; ans ans» y sin(x) 6.23e-7 sin(x) y» exp(acos(.3)) ans ans 3.547» z asin(y) 3.547 asin(y) z.578.578 A Note about Workspace: Numbers stored in double-precion floating point format Semicolon suppresses screen output Results assigned to ans if name not specified () parentheses for function inputs whos: Lt current variables clear: Clear variables and functions from memory cd: Change current working directory ls: Lt files in directory

Getting help help command lookfor command Printable Documents Matlabroot\help\pdf_doc\ (>>help) (>>lookfor) Matrices Entering and Generating Matrices Subscripts Scalar Expansion Concatenation Deleting Rows and Columns Array Extraction Matrix and Array Multiplication 2 Entering Numeric Arrays The Matrix in MATLAB 3 Row separator semicolon (;) Column separator space / comma (,)» a[ a[ 2;3 2;3 4] 4] a Use square 2 brackets [ ] 3 4» b[-2.8, b[-2.8, sqrt(-7), sqrt(-7), (3+5+6)*3/4] (3+5+6)*3/4] b -2.8-2.8 + 2.6458i 2.6458i.5.5» b(2,5) b(2,5) 23 23 b -2.8-2.8 + 2.6458i 2.6458i.5.5 23. 23. Any MATLAB expression can be entered as a matrix element Matrices must be rectangular. (Set undefined elements to zero) 4 A 2 Rows (m) 3 4 5 Columns (n) 2 3 4 5 4 6 2 6 6 2 8.2 9 4 25 2 7 2 7 22 7.2 5 7 3 8 3 8 23.5 4 5 56 4 9 4 9 24 23 83 3 5 5 2 25 A (2,4) A (7) Rectangular Matrix: Scalar: -by- array Vector: m-by- array -by-n array Matrix: m-by-n array Entering Numeric Arrays Numerical Array Concatenation 5 Scalar expansion Creating sequences: colon operator (:) Utility functions for creating matrices.» w[ w[ 2;3 2;3 4] 4] + 5 w 6 7 8 9» x :5 :5 x 2 3 4 5» y 2:-.5: 2:-.5: y 2. 2..5.5...5.5» z rand(2,4) rand(2,4) z.95.95.668.668.893.893.4565.4565.23.23.486.486.762.762.85.85 6 Use [ ] to combine exting arrays as matrix elements Row separator: semicolon (;) Column separator: space / comma (,)» a[ a[ 2;3 2;3 4] 4] a Use square 2 brackets [ ] 3 4» cat_a[a, cat_a[a, 2*a; 2*a; 3*a, 3*a, 4*a; 4*a; 5*a, 5*a, 6*a] 6*a] cat_a cat_a 2 2 4 3 4 6 8 3 6 4 8 9 2 2 2 2 6 6 4*a 5 6 2 2 5 5 2 2 8 8 24 24 Note: The resulting matrix must be rectangular

Deleting Rows and Columns Array Subscripting / Indexing» A[ A[ 5 9;4 9;4 3 2.5; 2.5;.. 3i+] 3i+] A.. 5. 5. 9. 9. 4. 4. 3. 3. 2.5 2.5.....+3.i.+3.i» A(:,2)[] A(:,2)[] A.. 9. 9. 4. 4. 2.5 2.5.... + 3.i 3.i» A(2,2)[] A(2,2)[]?????? Indexed Indexed empty empty matrix matrix assignment assignment not not allowed. allowed. A A(3,) A(3) 2 3 4 5 2 3 4 5 4 6 2 6 6 2 8.2 9 4 25 2 7 2 7 22 7.2 5 7 3 8 3 8 23.5 4 5 56 4 9 4 9 24 23 83 3 5 5 2 25 A(:5,5) A(:,) A(:,5) A(:,) A(2:25) A(2:) A(4:5,2:3) A([9 4; 5]) 7 8 9 Matrix Multiplication» a [ [ 2 3 4; 4; 5 6 7 8]; 8];» b ones(4,3); ones(4,3);» c a*b a*b c 26 26 26 26 26 26 Array Multiplication [2x4]*[4x3] [2x4] [4x3] [2x3] a(2nd row).b(3rd column)» a [ [ 2 3 4; 4; 5 6 7 8]; 8];» b [:4; [:4; :4]; :4];» c a.*b a.*b c 4 9 6 6 5 2 2 2 2 32 32 c(2,4) a(2,4)*b(2,4) 2 Matrix Manipulation Functions zeros: Create an array of all zeros ones: Create an array of all ones eye: Identity Matrix rand: Uniformly dtributed random numbers diag: Diagonal matrices and diagonal of a matrix size: Return array dimensions repmat: Replicate and tile a matrix Matrix Manipulation Functions Elementary Math det: Matrix determinant inv: Matrix inverse eig: Evaluate eigenvalues and eigenvectors rank: Rank of matrix Logical Operators Math Functions Polynomial and Interpolation 2 25

Logical Operations Elementary Math Function 26 equal to > greater than < less than > Greater or equal < less or equal ~ not & and or finite(), etc.... all(), any() find» Mass Mass [-2 [-2 NaN NaN 3 3 - - Inf Inf 3]; 3];» each_pos each_pos Mass> Mass> each_pos each_pos» all(mass>) all(mass>)» any(mass>) any(mass>)» pos_fin pos_fin (Mass>)&(finite(Mass)) (Mass>)&(finite(Mass)) pos_fin pos_fin Note: TRUE FALSE 27 abs, sign: Absolute value and Signum Function sin, cos, asin, acos : Triangular functions exp, log, log: Exponential, Natural and Common (base ) logarithm ceil, floor: Round toward infinities fix: Round toward zero Elementary Math Function round: Round to the nearest integer sqrt: Square root function real, imag: Real and Image part of complex rem: Remainder after divion Elementary Math Function max, min: Maximum and Minimum of arrays mean, median: Average and Median of arrays std, var: Standard deviation and variance sort: Sort elements in ascing order sum, prod: Summation & Product of Elements 28 Importing and Exporting Data Using the Import Wizard Using Save and Load command Input/Output for Text File Read formatted data, reusing the format string N times.»[a An]textread(filename,format,N) save save fname fname save save fname fname x y z save save fname fname -ascii save save fname fname -mat -mat load load fname fname load load fname fname x y z load load fname fname -ascii load load fname fname -mat -mat Import and Exporting Numeric Data with General ASCII delimited files» M dlmread(filename,delimiter,range) 32 33

Graphics Fundamentals Graphics Basic Plotting plot, title, xlabel, grid, leg, hold, ax Editing Plots Property Editor Mesh and Surface Plots meshgrid, mesh, surf, colorbar, patch, hidden Handle Graphics 35 36 2-D Plotting Sample Plot Syntax: Title plot(x, y, y, 'clm', x2, x2, y2, y2, 'clm2',...)...) Example: 37 x[:.:2*pi]; ysin(x); zcos(x); plot(x,y,x,z,'linewidth',2) title('sample Plot','fontsize',4); xlabel('x values','fontsize',4); ylabel('y values','fontsize',4); leg('y data','z data') grid grid on on 38 Ylabel Leg Xlabel Grid Subplots Syntax: subplot(rows,cols,index)»subplot(2,2,);»»subplot(2,2,2)»...... Surface Plot Example x :.:2; :.:2; y :.:2; :.:2; [xx, [xx, yy] yy] meshgrid(x,y); meshgrid(x,y); zzsin(xx.^2+yy.^2); surf(xx,yy,zz) surf(xx,yy,zz) xlabel('x xlabel('x axes') axes') ylabel('y ylabel('y axes') axes')»subplot(2,2,3)»......»subplot(2,2,4)»...... 39 4

3-D Surface Plotting contourf-colorbar-plot3-waterfall-contour3-mesh-surf Specialized Plotting Routines bar-bar3h-ht-area-pie3-rose 4 42 Editing and Debugging M-Files Debugging 43 What an M-File? The Editor/Debugger Search Path Debugging M-Files Types of Errors (Syntax Error and Runtime Error) Using keyboard and ; statement Setting Breakpoints Stepping Through Continue, Go Until Cursor, Step, Step In, Step Out Examining Values Selecting the Workspace Viewing Datatips in the Editor/Debugger Evaluating a Selection 44 Select Workspace Set Auto- Breakpoints tips Script and Function Files Programming and Dubugging Script Files Work as though you typed commands into MATLAB prompt Variable are stored in MATLAB workspace 45 46 Function Files Let you make your own MATLAB Functions All variables within a function are local All information must be passed to functions as parameters Subfunctions are supported

Basic Parts of a Function M-File Flow Control Statements 47 Output Arguments Function Name Input Arguments Online Help function y mean (x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) a row vector % containing the mean value of each column. [m,n] size(x); if m Function Code m n; y sum(x)/m; 48 if Statement if if ((attance ((attance > >.9).9) & (grade_average (grade_average > > 6)) 6)) pass pass ; ; ; ; while Loops eps eps ; ; while while (+eps) (+eps) > eps eps eps/2; eps/2; eps eps eps*2 eps*2 49 Flow Control Statements for Loop a a zeros(k,k) zeros(k,k) % % Preallocate Preallocate matrix matrix for for m m :k :k for for n n :k :k a(m,n) a(m,n) /(m+n /(m+n -); -); switch Statement method method 'Bilinear'; 'Bilinear'; switch switch lower(method) lower(method) case case {'linear','bilinear'} {'linear','bilinear'} dp('method dp('method linear') linear') case case 'cubic' 'cubic' dp('method dp('method cubic') cubic') otherwe otherwe dp('unknown dp('unknown method.') method.') Method Method linear linear 5 M-file Programming Features SubFunctions Varying number of input/output arguments Local and Global Variables Obtaining User Input Prompting for Keyboard Input Pausing During Execution Errors and Warnings Dplaying error and warning Messages Shell Escape Functions (! Operator) Optimizing MATLAB Code Vectorizing loops Preallocating Arrays Function M-file Data Types function function r ourrank(x,tol) ourrank(x,tol) % rank rank of of a matrix matrix s svd(x); svd(x); if if (nargin (nargin ) ) tol tol max(size(x)) max(size(x)) * s()* s()* eps; eps; r sum(s sum(s > tol); tol); Multiple Input Arguments use ( )»rourrank(rand(5),.); 5 function function [mean,stdev] [mean,stdev] ourstat(x) ourstat(x) [m,n] [m,n] size(x); Multiple Output size(x); if if m Arguments, use [ ] m n; n;»[m std]ourstat(:9); mean mean sum(x)/m; sum(x)/m; stdev stdev sqrt(sum(x.^2)/m sqrt(sum(x.^2)/m mean.^2); mean.^2); 52 Numeric Arrays Multidimensional Arrays Structures and Cell Arrays

Multidimensional Arrays Structures 53 The first references array dimension, the row. The second references dimension 2, the column. The third references dimension 3, The page. 2 3 3 6 8 5 7 6 2 9 2 3 4 4 4 5 3 6 4 2 Page Page N» A pascal(4);» A(:,:,2) A(:,:,2) magic(4) magic(4) A(:,:,) A(:,:,) 2 3 4 3 6 4 2 2 A(:,:,2) A(:,:,2) 6 6 2 3 3 3 5 8 9 7 6 2 2 4 4 4 5 5» A(:,:,9) A(:,:,9) diag(ones(,4)); 54 Arrays with named data containers called fields.» patient.name'john Doe'; Doe';» patient.billing 27.;» patient.test [79 [79 75 75 73; 73; 8 8 78 78 77.5; 22 22 2 2 25]; 25]; Also, Build structure arrays using the struct function. Array of structures» patient(2).name'katty Thomson';» Patient(2).billing.;» Patient(2).test [69 [69 25 25 33; 33; 2 2 28 28 77.5; 22 22 2 2 25]; 25]; Cell Arrays Array for which the elements are cells and can hold other MATLAB arrays of different types.» A(,) {[ {[ 4 3; 3; 5 8; 8; 7 2 9]}; 9]};» A(,2) {'Anne Smith'};» A(2,) {3+7i};» A(2,2) {-pi:pi/:pi}; Next Tutorial Session Image Processing Toolbox Movie Making Problem Set 55 Using braces {} to point to elements of cell array Using celldp function to dplay cell array Getting more help Contact http://www.mathworks.com/support You can find more help and FAQ about mathworks products on th page. Getting started with Matlab http://www.indiana.edu/~statmath/math/matlab/gettings tarted/index.html Matlab Primer http://math.ucsd.edu/~driver/2d-s99/matlabprimer.html Questions?? 69 7