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

Similar documents
Introduction to Matlab

Introduction to Engineering gii

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

1 Introduction to Matlab

1. Register an account on: using your Oxford address

Introduction to MatLab. Introduction to MatLab K. Craig 1

MATLAB QUICK START TUTORIAL

Introduction to MATLAB

Chapter 1 Introduction to MATLAB

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Introduction to MATLAB Practical 1

MatLab Just a beginning

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

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

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

PART 1 PROGRAMMING WITH MATHLAB

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

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

Programming in Mathematics. Mili I. Shah

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

Laboratory 1 Octave Tutorial

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

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Basic stuff -- assignments, arithmetic and functions

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

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

Matlab Programming Introduction 1 2

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Lab 1 - Worksheet Spring 2013

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

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

Introduction to MATLAB

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Matlab and Octave: Quick Introduction and Examples 1 Basics

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

Some elements for Matlab programming

2.0 MATLAB Fundamentals

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

MATLAB BEGINNER S GUIDE

Introduction to Matlab

To start using Matlab, you only need be concerned with the command window for now.

Programming 1. Script files. help cd Example:

MATLAB SUMMARY FOR MATH2070/2970

EP375 Computational Physics

Mechanical Engineering Department Second Year (2015)

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

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

A Brief Introduction to MATLAB

Introduction to MATLAB

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

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

MATH 3511 Basics of MATLAB

Introduction to Matlab

Basic Graphs. Dmitry Adamskiy 16 November 2011

AMS 27L LAB #1 Winter 2009

Programming in MATLAB

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

Matlab Tutorial and Exercises for COMP61021

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

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

Introduction to MATLAB

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

A Guide to Using Some Basic MATLAB Functions

Introduction to Python Practical 1

QUICK INTRODUCTION TO MATLAB PART I

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

Introduction to MATLAB

A Quick Tutorial on MATLAB. Zeeshan Ali

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

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

MATH 5520 Basics of MATLAB

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

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

Introduction to MATLAB

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

Lecturer: Keyvan Dehmamy

Introduction to Matlab

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

MATLAB and Numerical Analysis

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

A General Introduction to Matlab

AMS 27L LAB #2 Winter 2009

Digital Image Analysis and Processing CPE

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

Dr Richard Greenaway

Introduction to MATLAB LAB 1

Introduction to MATLAB

A QUICK INTRODUCTION TO MATLAB

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

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

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

Consider this m file that creates a file that you can load data into called rain.txt

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

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

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Table of Contents. Basis CEMTool 7 Tutorial

PRACTICAL file. Department: Computer Science and Engineering. Simulation and Modeling Lab. Subject Code: BTCS 607. Semester:

Python Programming: An Introduction to Computer Science

Transcription:

What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful graphic tools; pictures in 2D/3D Is a programming language Close to scripting language, has structures such as looping, function calls 1 2 What is MATLAB? A programming environment Many toolboxes (signal processing, image processing, ) and simulation tools (Simulink) An application development tool MATLAB programs can be exported to become an application Graphical user interfaces can be developed under MATLAB to allow interaction with Programming Environment Directory, workspace, etc. Command History Window Command Window user 3 4

Using MATLAB as a calculator Built-in operators and functions Command Window Giving commands to MATLAB E.g., evaluate mathematical expressions using the MATLAB programming syntax Compute 5sin(2.5 3- )+1/75 Type Command prompt Constants Operators Function 5 Operation, function or constant MATLAB command Operation, function or constant MATLAB command + (addition) + sin x sin(x) -(subtraction) - cos x cos(x) (multiplication) * tan x tan(x) / (division) / cot x cot(x) x (absolute value of abs(x) arcsin x asin(x) x) square root of x sqrt(x) arccos x acos(x) e x exp(x) arctan x atan(x) ln x (natural log) log(x) arccot x acot(x) log 10 x (base 10 log) log10(x) n! (n factorial) gamma(n+1) p (3.14159265...) pi e (2.71828...) exp(1) i (imaginary unit, i sqrt(-1)) 6 Built-in operators and functions Vectors and Matrices Type help to find out information of MATLAB functions MATLAB is tailor-designed for vector and matrix operations To define a vector: x = [ 1 2 3 4 5 6 7 8 9 10]; 7 A variable with name x A vector with 10 elements. The number is the value of each element We often use a ; at the end of each statement. Without it, MATLAB will echo your statement when you hit return 8

Matrix Form (1) 2x+3y=9 x-2y=-13 (3) 6x+y=9-5x-3y=7 3x-10y=-4 2 3 x 9 1 2 y 13 22 21 21 6 1 9 x 5 3 7 y 3 10 4 21 32 31 9 A Matrix Multiplication 4 10 3 4 B 3 8 Check the size first A: 1 x 3 B: 3 x 1 AB 1x1 (a scalar) AB = 4(-4) + (-10)(3) + 3(8) = -22 BA: 3 x 3 4 16 40 12 BA 3 4 10 3 12 30 9 8 32 80 24 10 Matrix Multiplication Matrix Multiplication 8 5 3 1 3 0 4 3 10 2 A C 2 5 8 9 2 0 4 1 7 5 AC=? A: 2 x 4, C: 4x3 AC: 2 x 3 8 5 3 1 3 0 4 3 10 2 13 53 17 AC 2 5 8 9 2 0 4 56 23 81 1 7 5 AB in general not equal to BA 3 1 7 1 4 9 A 10 1 8 B 6 2 1 5 2 4 7 4 47 40 38 77 8 23 3 AB 60 10 33 BA 43 6 22 45 0 19 26 11 45 11 12

Vectors Matrices x = [ 1 2 3 4 5 6 7 8 9 10]; Can also be written as x = 1:10; or x = 1:1:10; Examples: x2 = 1:0.1:1.5; Means a vector starts with a number 1 Means the next element will add 1 to the previous element x2 = [1 1.1 1.2 1.3 1.4 1.5]; To access the first element: x2(1) give 1 Means a vector ends with a number 10 To access the third element: x2(3) give 1.2 13 Get the element of the 1 st and 2 nd column, of A i.e. 2 Get all the elements in the 1 st row of A i.e. 1,2,3 Get all the elements in the 2 nd column of A i.e. 2,5,8 14 Vector and matrix operations Multiplication of vectors and matrices Arithmetic operations can be applied to vectors and matrix x=[1 2 3]; x + y [-1 3 6]; y=[-2 1 3]; x - y [3 1 0]; a=2; a*x [2 4 6]; x(1)*y(3) 3; a: 2 x 3, b: 3 x 2 a*b 2x2 matrix x*y??? Error using ==> mtimes Inner matrix dimensions must agree. 15 16

Element-based operation of matrices If we want to multiply two matrices element by element, we can use. operator Matrix operations Functions Operation carried out det(a) Determinant of matrix A inv(a) Matrix inverse \ Left division (solving linear system) rank(a) or rank([a b]) Number of linearly independent rows or columns expm Matrix exponential lu LU factorization (Gaussian elimination) qr QR factorization chol Cholesky factorization eig Eigenvalue decomposition svd Singular value decomposition 17 18 Plotting graphs Plotting graphs plot: creates linear plots of vectors and matrices t = 0:0.001:0.1; y = 3*cos(2*pi*50*t); plot(t,y, --b ) xlabel( t ) ylabel( y(t) ) title( Cosine wave ) Define a vector t with value from 0 to 0.1 and a step size of 0.001 For each element of t, compute y based on the formulation Plot y against t with option: dash blue line 19 20

Other options of plot Obtain sufficient data for plotting plot(x,y,option) Symbol Color Symbol Style k black. Point b blue o Circle c cyan x x-mark g green + Plus m magenta * Star r red - Solid w white : Dotted y yellow -. Dashdot -- Dashed 21 t = 0:0.001:0.1; y = 3*cos(2*pi*50*t); plot(t,y, --b ) xlabel( t ) ylabel( y(t) ) title( Cosine wave ) Why 0.001? With step size = 0.01 22 Obtain sufficient data for plotting User-defined functions t = 0:0.001:0.1; y = 3*cos(2*pi*50*t); plot(t,y, --b ) xlabel( t ) ylabel( y(t) ) title( Cosine wave ) The cosine wave has a frequency of 50 hertz, i.e. 50 cycle per second Each cycle will last 1/50 = 0.02 second Setting step size = 0.001 ensures for each cycle there are 0.02/0.001 = 20 data to plot on the graph We can define our own functions MATLAB programming Better planning of the logical flow of the commands Facilitate the access of some frequently used routines M-file: plain text file containing MATLAB commands and saved with extension.m There are two types: scripts and functions 23 24

M-file Function M-file Script M-file Contains only the MATLAB commands Similar to a batch file : putting together a number of commands in a batch and run sequentially Function M-file Develop user-defined functions Contains some special program constructs in addition to the commands 25 The function M file should start with the following statement: function y=<function_name>(argument list) A keyword of MATLAB that indicates this M-file stores a function A list of output parameters The function name. Better to be the same as the file name A list of input parameters of the function 26 Example Comments Define a function called funcx that will compute the following equation Input parameters: x1, x2 Output parameter: y Comments are indicated by a percent sign % Any text on the same line after a percent sign is ignored Good practice to add comment Purpose of the function Information about input parameters Information about output parameters 27 28

function y = funcx(x1,x2) % This is a function for computing the % equation y = x1^2+(1-e^x2)^2-4 % Input parameters: % x1, x2: the two input numbers % Output parameter: % y: The result of the computation y = x1.^2 + (1 - exp(x2)).^2 4; 29 30 Conditionals: if if isinf(x) ~isreal(x) % Is x infinite or imag? disp( Bad input! )% If yes, show error mess y = NaN;% and set y as Not A Number (NaN) elseif (x < 1000) && (x > 0) % Else if disp( x is between 0 to 1000 ); y = x; else % If the above two conditions are not y = 0; % fulfilled, set y = 0 end 31 Relational and logical operators Logical operator: (isinf): return T or F Relational operators: == equal to ~= not equal to < less than > greater than <= less than or equal to >= greater than or equal to Logical operators: && short-circuited scalar logical AND & bitwise logical AND short-circuited scalar logical OR bitwise logical OR ~ logical NOT 32

Example && can only be applied to scalar The first condition is fulfilled, hence will not evaluate the second one The first condition is not fulfilled, hence continue Conditional: switch switch units % Test the variable units, % which is a string case length % If equal to length disp( meters ) % then case volume % If equal to volume disp( liters ) % then case time disp( seconds ) otherwise % If all of the above is false disp( I give up ) % Display I give up end evaluate the second one 33 34 Loops: for Loops: while nmin = 3; nmax = 10; f = zeros(1,nmax); % Clearly define the f(1:2) = 1; % total memory needed for n = nmin:nmax f(n) = f(n-1) + f(n-2); % This statement will be executed % 8 times, from n = 3 to 10 end n = 0; while x > 1 % While x > 1, do the x = x/2; % following iteratively n = n+1; if n > 50, break, end % If n>50, out end % out from the % loop 35 36

Matlab is not good at handling loops Better to replace loops with vector operations Exercise 1 Give the MATLAB commands that evaluate the following equation and plot the result: For loop Vector operation generates the same set of results 37 38 set of results Solution 1 >> x = >> y = >> plot(x,y,'--r') >> xlabel('x') >> ylabel('y') >> title('gaussian function') 39 Exercise 2 Consider: Using the for loop, develop a MATLAB function to implement the above equation Syntax: y = natural_log(x,n) Remember to check if the absolute value of x and n that the user input are smaller than 1 and greater than 0, respectively Error message is generated if not Add comments 40

Solution function y = natural_log(x,n) % This function computes % % Input parameters: % % % % Output parameter: % if Solution % Check if n is greater than 0 % and abs(x) is smaller than 1 % If yes, implement the equation elseif % show a warning message and quit disp('warning: n is smaller than 0') else % If abs(x) >= 1, % show a warning message and quit 41 end 42 Exercise 3 For the function natural_log(x,n) in Exercise 2 Convert that to using vector operations Hint: the function sum(v) can take the sum of all elements in the vector v Summary Introduction to MATLAB programming Basic arithmetic operations x*y x.* y Looping: for, while Prefer to use vector calculations rather than looping Functions 43 44

References M.J. Roberts, Fundamentals of Signals & Systems, McGraw-Hill, 2008. James H. McClellan, Ronald W. Schafer and Mark A. Yoder, Signal Processing First, Prentice-Hall, 2003. T.A. Driscoll, Learning Matlab, Philadelphia, PA: Society for Industrial and Applied Mathematics, c2009. Using Matlab, The Math Works Inc. 45