M ATLAB Tutorial Course 1. Contents Continued  Desktop tools  matrices  Logical &Mathematical operations  Handle Graphics  Ordinary Differential.

Slides:



Advertisements
Similar presentations
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Advertisements

Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
MATLAB - Basics Centro de Informática Universidade Federal de Pernambuco Aprendizagem de Máquina – IN1102 Arley Ristar –
Introdução ao M ATLAB M ATLAB Basico
Introduction to MATLAB Simon O’Keefe Non-Standard Computation Group
Dr. Jie Zou PHY Welcome to PHY 3320 Computational Methods in Physics and Engineering.
EGR 105 Foundations of Engineering I Session 3 Excel – Basics through Graphing Fall 2008.
Matlab intro The Environment
MATLAB Fundamentals.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Signals and Systems Laboratory 2013 Teacher: Marek OssowskiTeacher: Marek Ossowski Phone: , Room 14, C3,
1 Prof. Nizamettin AYDIN Biosignals and Systems.
MATLAB Second Seminar. Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill.
1 M ATLAB Short Course. History of Calculator 2 3 Introduction to Matlab Matlab is short for Matrix Laboratory Matlab is also a programming language.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
Introduction to MATLAB
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
Lesson 4 Arrays in MATLAB First round Lecturer : Dr. Noam Amir Format Revised CE2002-NTUST.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
Introduction to MATLAB CBE 502 Mathematical Methods of Engineering Analysis.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
1 MATLAB Basics. 2 MATLAB Documentation /help/techdoc/ Matrix Algebra.
INTRODUCTION TO MATLAB LAB# 01
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Recap Script M-file Editor/Debugger Window Cell Mode Chapter 3 “Built in MATLAB Function” Using Built-in Functions Using the HELP Feature Window HELP.
CDA6530: Performance Models of Computers and Networks Chapter 4: Using Matlab for Performance Analysis and Simulation TexPoint fonts used in EMF. Read.
1 M ATLAB Short Course Part (2). 2 Elementary Math Function abs, sign: Absolute value and Signum Function sin, cos, asin, acos…: Triangular functions.
ME451 Kinematics and Dynamics of Machine Systems MATLAB  Tutorial September 16, 2014 Dan Negrut University of Wisconsin-Madison 1.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
OUTLINE Overview Numbers, variables and similar in Matlab
M ATLAB Tutorial Covered by: Toby Heyn University of Wisconsin, Madison.
INTRODUCTION TO MATLAB MATLAB is a software package for computation in engineering, science, and applied mathemat-ics. It offers a powerful programming.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Introduction to Matlab By E. Noura Semary. Contents MATLAB Environment  Command window, Workspace, Path window, Editor window,and Figure window) Basic.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
MATLAB Lecture Two Tuesday 5 July Chapter 3.
A Quick Octave Tutorial 阮 翀
Introduction to Matlab
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
MATLAB Constants, Variables & Expression Nafees Ahmed Asstt. Professor, EE Deptt DIT, DehraDun.
Introduction to Matlab Engr. Mian Shahzad Iqbal LAB NO.2
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
What is Matlab?  “MATLAB® is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB,
Numeric, Cell and Structural Arrays One of the strenghts of MATLAB is the capabilty to handle collection of numbers called ARRAYS. MATLAB refers to scalars,
MATLAB Tutorial Course
MATLAB DENC 2533 ECADD LAB 9.
Introduction to Matlab
Matlab Workshop 9/22/2018.
StatLab Matlab Workshop
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Lecture 2 Introduction to MATLAB
Introduction to Matlab
INTRODUCTION TO MATLAB
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Presentation transcript:

M ATLAB Tutorial Course 1

Contents Continued  Desktop tools  matrices  Logical &Mathematical operations  Handle Graphics  Ordinary Differential Equations (ODE) 4

MATLAB Desktop Tools Command Window Command History Help Browser Workspace Browser Editor/Debugger 8

Calculations at the Command Line »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = Results assigned to “ans” if name not specified () parentheses for function inputs Semicolon suppresses screen output MATLAB as a calculator Assigning Variables A Note about Workspace: Numbers stored in double-precision floating point format » -5/( )^2 ans = » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = e-017 » exp(acos(0.3)) ans = » -5/( )^2 ans = » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = e-017 » exp(acos(0.3)) ans =

General Functions whos: List current variables clear: Clear variables and functions from memory Close: Closes last figures cd: Change current working directory dir: List files in directory echo: Echo commands in M-files format: Set output format 10

Getting help help command ( >>help ) lookfor command ( >>lookfor ) Help Browser ( >>doc ) helpwin command ( >>helpwin ) Search Engine Printable Documents “ Matlabroot\help\pdf_doc\ ” Link to The MathWorks 11

Matrices Entering and Generating Matrices Concatenation Deleting Rows and Columns Array Extraction Matrix and Array Multiplication 12

»a=[1 2;3 4] a = »b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = i »b(2,5) = 23 b = i »a=[1 2;3 4] a = »b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = i »b(2,5) = 23 b = i Any MATLAB expression can be entered as a matrix element Matrices must be rectangular. (Set undefined elements to zero) Entering Numeric Arrays Row separator semicolon (;) Column separator space / comma (,) Use square brackets [ ] 13

The Matrix in MATLAB Rows (m) Columns (n) A = A (2,4) A (17) Rectangular Matrix: Scalar:1-by-1 array Vector:m-by-1 array 1-by-n array Matrix:m-by-n array 14

»w=[1 2;3 4] + 5 w = »x = 1:5 x = »y = 2:-0.5:0 y = »z = rand(2,4) z = »w=[1 2;3 4] + 5 w = »x = 1:5 x = »y = 2:-0.5:0 y = »z = rand(2,4) z = Scalar expansion Creating sequences: colon operator (:) Utility functions for creating matrices. Entering Numeric Arrays 15

Numerical Array Concatenation »a=[1 2;3 4] a = »cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = »a=[1 2;3 4] a = »cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] Note: The resulting matrix must be rectangular 4*a 16

Deleting Rows and Columns »A=[1 5 9; ; i+1] A = i »A(:,2)=[] A = i »A(2,2)=[] ??? Indexed empty matrix assignment is not allowed. »A=[1 5 9; ; i+1] A = i »A(:,2)=[] A = i »A(2,2)=[] ??? Indexed empty matrix assignment is not allowed. 17

Array Subscripting / Indexing A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) A(1:end,end) A(:,end) A(21:end)’ 18

Matrix Multiplication »a = [ ; ]; »b = ones(4,3); »c = a*b c = »a = [ ; ]; »b = ones(4,3); »c = a*b c = [2x4] [4x3] [2x4]*[4x3] [2x3] a(2nd row).b(3rd column) »a = [ ; ]; »b = [1:4; 1:4]; »c = a.*b c = »a = [ ; ]; »b = [1:4; 1:4]; »c = a.*b c = c(2,4) = a(2,4)*b(2,4) Array Multiplication 19

Matrix Manipulation Functions zeros : Create an array of all zeros ones : Create an array of all ones eye: Identity Matrix rand: Uniformly distributed random numbers diag: Diagonal matrices and diagonal of a matrix size: Return array dimensions 20

Matrix Manipulation Functions transpose ( ’ ): Transpose matrix rot90: rotate matrix 90 tril: Lower triangular part of a matrix triu: Upper triangular part of a matrix cross: Vector cross product dot: Vector dot product det: Matrix determinant inv: Matrix inverse eig: Evaluate eigenvalues and eigenvectors rank: Rank of matrix 21

Elementary Math Logical Operators Math Functions 25

Logical Operations » Mass = [-2 10 NaN Inf 31]; » each_pos = Mass>=0 each_pos = » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = » Mass = [-2 10 NaN Inf 31]; » each_pos = Mass>=0 each_pos = » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = = = equal to > greater than < less than >= Greater or equal <= less or equal ~ not & and | or isfinite(), etc.... all(), any() find Note: 1 = TRUE 0 = FALSE 26

Elementary Math Function abs, sign: Absolute value and Signum Function sin, cos, asin, acos…: Triangular functions exp, log, log10: Exponential, Natural and Common (base 10) logarithm ceil, floor: Round toward infinities fix: Round toward zero 27

Elementary Math Function round: Round to the nearest integer gcd: Greatest common devisor lcm: Least common multiple sqrt: Square root function real, imag: Real and Image part of complex rem: Remainder after division

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 ascending order sum, prod: Summation & Product of Elements 28

Graphics Fundamentals 35

Graphics Basic Plotting plot, title, xlabel, grid, legend, hold, axis Editing Plots Property Editor 36

2-D Plotting Syntax: Example: plot(x1, y1, 'clm1', x2, y2, 'clm2',...) x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z,'fontsize',14); legend('Y data','Z data,'linewidth',2) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values', data') grid on x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z,'fontsize',14); legend('Y data','Z data,'linewidth',2) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values', data') grid on 37

Sample Plot TitleYlabelXlabelGridLegend 38

Subplots Syntax: » subplot(2,2,1); » … » subplot(2,2,2) »... » subplot(2,2,3) »... » subplot(2,2,4) »... » subplot(2,2,1); » … » subplot(2,2,2) »... » subplot(2,2,3) »... » subplot(2,2,4) »... subplot(rows,cols,index) 39

Programming and Application Development 45

Script and Function Files Script Files Work as though you typed commands into MATLAB prompt Variable are stored in MATLAB workspace 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 46

Basic Parts of a Function M-File function y = mean (x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); if m == 1 m = n; end y = sum(x)/m; Output Arguments Input Arguments Function Name Online Help Function Code 47

if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; end; if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; end; eps = 1; while (1+eps) > 1 eps = eps/2; end eps = eps*2 eps = 1; while (1+eps) > 1 eps = eps/2; end eps = eps*2 if Statement while Loops Flow Control Statements 48

a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end method = 'Bilinear'; switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') otherwise disp('Unknown method.') end Method is linear method = 'Bilinear'; switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') otherwise disp('Unknown method.') end Method is linear for Loop switch Statement Flow Control Statements 49

Function M-file function r = ourrank(X,tol) % rank of a matrix s = svd(X); if (nargin == 1) tol = max(size(X)) * s(1)* eps; end r = sum(s > tol); function r = ourrank(X,tol) % rank of a matrix s = svd(X); if (nargin == 1) tol = max(size(X)) * s(1)* eps; end r = sum(s > tol); function [mean,stdev] = ourstat(x) [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2); function [mean,stdev] = ourstat(x) [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2); Multiple Input Arguments use ( ) Multiple Output Arguments, use [ ] »r=ourrank(rand(5),.1); »[m std]=ourstat(1:9); 51

Ordinary Differential Equations (Initial Value Problem) An explicit ODE with initial value: Using ode45 for non-stiff functions and ode23t for stiff functions. [t,y] = solver(odefun,tspan,y0,options) [initialtime finaltime] Initialvlue function dydt = odefun(t,y) Use odeset to define options parameter 58

ODE Example: » [t,y]=ode45( ' myfunc ',[0 20],[2;0]) function dydt=myfunc(t,y) dydt=zeros(2,1); dydt(1)=y(2); dydt(2)=(1-y(1)^2)*y(2)-y(1); Note: Help on odeset to set options for more accuracy and other useful utilities like drawing results during solving. 59

? ? 70