Introduction to MATLAB

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

-seminar 1 for digital signal processing
Programming Language Concepts
1.
Lab # 03- SS Basic Graphic Commands. Lab Objectives: To understand M-files principle. To plot multiple plots on a single graph. To use different parameters.
MATLAB – A Computational Methods By Rohit Khokher Department of Computer Science, Sharda University, Greater Noida, India MATLAB – A Computational Methods.
Chapter Three Arithmetic Expressions and Assignment Statements
Multidimensional Array
Types of selection structures
Chapter 11 Creating Framed Layouts Principles of Web Design, 4 th Edition.
StatLab Workshop Yale University Maximiliano Appendino, Economics October 18 th, 2013.
Introduction to MATLAB The language of Technical Computing.
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to Matlab
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
MATLAB Basics CS 111 Introduction to Computing in Engineering and Science.
Introduction to MATLAB
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
EGR 106 – Week 2 – Arrays & Scripts Brief review of last week Arrays: – Concept – Construction – Addressing Scripts and the editor Audio arrays Textbook.
Introduction to MATLAB
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Matlab intro The Environment
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.
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
How to Use MATLAB A Brief Introduction. 2 What can MATLAB do? Matrix Operations Symbolic Computations Simulations Programming 2D/3D Visualization.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
Introduction to MATLAB CBE 502 Mathematical Methods of Engineering Analysis.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
INTRODUCTION TO MATLAB LAB# 01
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
MATLAB Practice 1 Introducing MATLAB Lecture Notes on Video Search & Mining, Spring 2012 Presented by Jun Hee Yoo Biointelligence Laboratory School of.
Introduction to Engineering MATLAB – 2 Introduction to MATLAB - 2 Agenda Defining Variables MATLAB Windows.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introduction to Matlab. What is Matlab? A software environment for interactive numerical computations Examples:  Matrix computations and linear algebra.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
>> x = [ ]; y = 2*x y = Arrays x and y are one dimensional arrays called vectors. In MATLAB all variables are arrays. They allow functions.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
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 Lecture 1 염익준. Introduction MATLAB (MATrix LABoratory) a special purpose computer program optimized to perform engineering and scientific calculations.
1 Faculty Name Prof. A. A. Saati. 2 MATLAB Fundamentals 3 1.Reading home works ( Applied Numerical Methods )  CHAPTER 2: MATLAB Fundamentals (p.24)
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators.
ECE 1304 Introduction to Electrical and Computer Engineering
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
Introduction To MATLAB
StatLab Matlab Workshop
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Introduction to Matlab
INTRODUCTION TO MATLAB
Experiment No. (1) - an introduction to MATLAB
How to Use MATLAB A Brief Introduction.
CS 111 Introduction to Computing in Engineering and Science
Presentation transcript:

Introduction to MATLAB Sajid GUL khawaja

Introduction What is MATLAB ? MATLAB Stands for MATrix LABoratory. MATLAB is a computer program that combines computation and visualization power that makes it particularly useful tool for engineers. MATLAB is an executive program, and a script can be made with a list of MATLAB commands like other programming language. MATLAB Stands for MATrix LABoratory. The system was designed to make matrix computation particularly easy. The MATLAB environment allows the user to: manage variables import and export data perform calculations generate plots develop and manage files for use with MATLAB.

MATrix LABoratory www.mathworks.com Advantages of MATLAB Ease of use Platform independence Predefined functions Plotting Disadvantages of MATLAB Can be slow Commercial software

MATLAB Screen Command Window type commands Current Directory View folders and m-files Workspace View program variables Double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary

Variables No need for types. i.e., All variables are created with double precision unless specified and they are matrices. After these statements, the variables are 1x1 matrices with double precision int a; double b; float c; Example: >>x=5; >>x1=2;

Variables Types Variable types Numeric Logical Character and string Cell and Structure Function handle

Variables (con’t…) Variable names: Must start with a letter You’ll get an error if this doesn’t happen May contain only letters, digits, and the underscore “_” MATLAB is case sensitive, i.e. one & OnE are different variables. MATLAB only recognizes the first 31 characters in a variable name. Assignment statement: Variable = number; Variable = expression; Example: >> tutorial = 1234; >> tutorial = 1234 tutorial = 1234 NOTE: when a semi-colon ”;” is placed at the end of each command, the result is not displayed.

Variables (con’t…) Don’t name your variables the same as functions min, max, sqrt, cos, sin, tan, mean, median, etc Funny things happen when you do this MATLAB reserved words don’t work either i, j, eps, nargin, end, pi, date, etc i, j are reserved as complex numbers initially Will work as counters in my experience so they can be redefined as real numbers Give meaningful (descriptive and easy-to-remember) names for the variables. Never define a variable with the same name as a MATLAB function or command.

Special Variables Special Values MATLAB includes a number of predefined special values. These values can be used at any time without initializing them. These predefined values are stored in ordinary variables. They can be overwritten or modified by a user. If a new value is assigned to one of these variables, then that new value will replace the default one in all later calculations. >> circ1 = 2 * pi * 10; >> pi = 3; >> circ2 = 2 * pi * 10; Never change the values of predefined variables.

Special Variables (con’t…) ans : default variable name for the result pi:  = 3.1415926………… eps:  = 2.2204e-016, smallest amount by which 2 numbers can differ. Inf or inf : , infinity NaN or nan: not-a-number Commands involving variables: who: lists the names of defined variables whos: lists the names and sizes of defined variables clear: clears all varialbes, reset the default values of special variables. clear name: clears the variable name clc: clears the command window clf: clears the current figure and the graph window.

Interactive Commands Format of output Defaults to 4 decimal places Can change using format statement format long changes output to 15 decimal places

Operators (arithmetic) + addition - subtraction * multiplication / division ^ power ‘ complex conjugate transpose

Operators Scalar arithmetic operations Operation MATLAB form Exponentiation: ^ ab a^b Multiplication: * ab a*b Right Division: / a / b = a/b a/b Left Division: \ a \ b = b/a a\b Addition: + a + b a+b Subtraction: - a – b a-b MATLAB ignores white space between variables and operators

Operators (relational, logical) == Equal to ~= Not equal to < Strictly smaller > Strictly greater <= Smaller than or equal to >= Greater than equal to & And operator | Or operator

Operators (Element by Element) .* element-by-element multiplication ./ element-by-element division .^ element-by-element power

Order of Operations Parentheses Exponentiation Multiplication and division have equal precedence Addition and subtraction have equal precedence Evaluation occurs from left to right When in doubt, use parentheses MATLAB will help match parentheses for you

Vectors, Matrices and Arrays Array Operations Matrices

Vectors, Matrices and Arrays The fundamental unit of data in MATLAB Scalars are also treated as arrays by MATLAB (1 row and 1 column). Row and column indices of an array start from 1. Arrays can be classified as vectors and matrices.

Vectors, Matrices and Arrays Vector: Array with one dimension Matrix: Array with more than one dimension Size of an array is specified by the number of rows and the number of columns, with the number of rows mentioned first (For example: n x m array). Total number of elements in an array is the product of the number of rows and the number of columns.

Arrays Variables and Arrays Array: A collection of data values organized into rows and columns, and known by a single name. Row 1 Row 2 Row 3 arr(3,2) Row 4 Col 1 Col 2 Col 3 Col 4 Col 5

1x4 array  4 elements, row vector 1 2 3 4 5 6 a= 3x2 matrix  6 elements b=[1 2 3 4] 1x4 array  4 elements, row vector 1 3 5 c= 3x1 array  3 elements, column vector a(2,1)=3 b(3)=3 c(2)=3 Row # Column #

Vectors x is a row vector. y is a column vector. A row vector in MATLAB can be created by an explicit list, starting with a left bracket, entering the values separated by spaces (or commas) and closing the vector with a right bracket. A column vector can be created the same way, and the rows are separated by semicolons. Example: >> x = [ 0 0.25*pi 0.5*pi 0.75*pi pi ] OR x = [ 0 0.25*pi, 0.5*pi, 0.75*pi , pi] x = 0 0.7854 1.5708 2.3562 3.1416 >> y = [ 0; 0.25*pi; 0.5*pi; 0.75*pi; pi ] y = 0.7854 1.5708 2.3562 3.1416 x is a row vector. y is a column vector.

NOTE: MATLAB index starts at 1. Vectors (con’t…) Vector Addressing – A vector element is addressed in MATLAB with an integer index enclosed in parentheses. Example: >> x(3) ans = 1.5708  3rd element of vector x The colon notation may be used to address a block of elements. (start : increment : end) start is the starting index, increment is the amount to add to each successive index, and end is the ending index. A shortened format (start : end) may be used if increment is 1. Example: >> x(1:3) ans = 0 0.7854 1.5708  1st to 3rd elements of vector x NOTE: MATLAB index starts at 1.

Vectors x = start:increment:end Some useful commands: x = start:end create row vector x starting with start, counting by one, ending at end x = start:increment:end create row vector x starting with start, counting by increment, ending at or before end length(x) returns the length of vector x y = x’ transpose of vector x dot (x, y) returns the scalar dot product of the vector x and y.

first: increment: last Arrays and Matrices Initializing with Shortcut Expressions first: increment: last Colon operator: a shortcut notation used to initialize arrays with thousands of elements >> x = 1 : 2 : 10; >> angles = (0.01 : 0.01 : 1) * pi; Transpose operator: (′) swaps the rows and columns of an array >> g = [1:4]; >> h = [ g′ g′ ]; 1 1 2 2 3 4 4 h=

Long Array, Matrix t =1:10 k =2:-0.5:-1 B = [1:4; 5:8] 1 2 3 4 5 6 7 8 9 10 k =2:-0.5:-1 k = 2 1.5 1 0.5 0 -0.5 -1 B = [1:4; 5:8] x = 1 2 3 4 5 6 7 8

Matrices Addressing recall: f = 1 2 3 4 5 6 h = 2 4 6 1 3 5 Matrix Addressing: -- matrixname(row, column) -- colon may be used in place of a row or column reference to select the entire row or column. Example: >> f(2,3) ans = 6 >> h(:,1) 2 1 recall: f = 1 2 3 4 5 6 h = 2 4 6 1 3 5

Generating Vectors/Matrices from functions zeros(M,N) MxN matrix of zeros ones(M,N) MxN matrix of ones rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1) x = zeros(1,3) x = 0 0 0 x = ones(1,3) 1 1 1 x = rand(1,3) 0.9501 0.2311 0.6068

Subarrays Subarrays The end function: When used in an array subscript, it returns the highest value taken on by that subscript. arr3 = [1 2 3 4 5 6 7 8]; arr3(5:end) is the array [5 6 7 8] arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; arr4(2:end, 2:end)

Subarrays (con’t…) Subarrays Assigning a Scalar to a Subarray: A scalar value on the right-hand side of an assignment statement is copied into every element specified on the left-hand side. >> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; >> arr4(1:2, 1:2) = 1 arr4 = 1 1 3 4 1 1 7 8 9 10 11 12

Array Operations Scalar-Array Mathematics For addition, subtraction, multiplication, and division of an array by a scalar simply apply the operations to all elements of the array. Example: >> f = [ 1 2; 3 4] f = 1 2 3 4 >> g = 2*f – 1 g = 1 3 5 7 Each element in the array f is multiplied by 2, then subtracted by 1.

Array Operations (con’t…) Element-by-Element Array-Array Mathematics. Operation Algebraic Form MATLAB Addition a + b Subtraction a – b Multiplication a x b a .* b Division a  b a ./ b Exponentiation ab a .^ b Example: >> x = [ 1 2 3 ]; >> y = [ 4 5 6 ]; >> z = x .* y z = 4 10 18 Each element in x is multiplied by the corresponding element in y.

Matrices Some Useful Commands Length(A) returns the larger of the number of rows or columns in A. Size(A) for a m x n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix. Transpose B = A’ Identity Matrix eye(n)  returns an n x n identity matrix eye(m,n)  returns an m x n matrix with ones on the main diagonal and zeros elsewhere. Addition and subtraction C = A + B C = A – B Scalar Multiplication B = A, where  is a scalar. Matrix Multiplication C = A*B Matrix Inverse B = inv(A), A must be a square matrix in this case. rank (A)  returns the rank of the matrix A. Matrix Powers B = A.^2  squares each element in the matrix C = A * A  computes A*A, and A must be a square matrix. Determinant det (A), and A must be a square matrix. A, B, C are matrices, and m, n,  are scalars.

Initializing with Keyboard Input The input function displays a prompt string in the Command Window and then waits for the user to respond. my_val = input( ‘Enter an input value: ’ ); in1 = input( ‘Enter data: ’ ); in2 = input( ‘Enter data: ’ ,`s`);

Displaying Data in MATLAB The disp (Array/String) function >> disp( 'Hello' ) Hello >> disp(5) 5 >> disp( [ ‘Hello ' ‘World!' ] ) Hello World! >> name = ‘World!'; >> disp( [ 'Hello ' name ] )

Display Windows Graphic (Figure) Window M-file editor/debugger window Displays plots and graphs Created in response to graphics commands. M-file editor/debugger window Create and edit scripts of commands called M-files.

Plotting >> plot ( variablename, ‘symbol’) For more information on 2-D plotting, type help graph2d Plotting a point: >> plot ( variablename, ‘symbol’) the function plot () creates a graphics window, called a Figure window, and named by default “Figure No. 1” Example : Complex number >> z = 1 + 0.5j; >> plot (z, ‘.’)

Basic Task: Plot the function sin(x) between 0≤x≤4π Create an x-array of 100 samples between 0 and 4π. Calculate sin(.) of the x-array Plot the y-array >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y)

Display Facilities plot(.) stem(.) Example: >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y) >>plot(x,y) Example: >>stem(y) >>stem(x,y)

Display Facilities title(.) xlabel(.) ylabel(.) >>title(‘This is the sinus function’) >>xlabel(‘x (secs)’) >>ylabel(‘sin(x)’)

MATLAB Graphs x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function')

Multiple Graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on

Selection Programming Flow Control Loops

Flow Control (if/else) Simple if statement: if logical expression commands end Example: (Nested) if d <50 count = count + 1; disp(d); if b>d b=0; Example: (else and elseif clauses) if temperature > 100 disp (‘Too hot – equipment malfunctioning.’) elseif temperature > 90 disp (‘Normal operating range.’); elseif (‘Below desired operating range.’) else disp (‘Too cold – turn off equipment.’)

Switch, Case, and Otherwise switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end More efficient than elseif statements Only the first matching case is executed The switch statement is a convenient way to execute conditional code when you have many possible cases to choose from. This function can be used in place of a series of elseif statements. The code above shows a simple example of the switch statement. It checks the variable input_num for certain values. If input_num is -1, 0, or 1, the case statements display the value on screen as text. If input_num is none of these values, execution drops to the otherwise statement and the code displays the test ‘other value’. Only the first matching case is executed. This function could also be created using IF / ELSEIF / ELSE commands: if input_num == -1 disp(‘negative one’); elseif input_num == 0 disp(‘zero’); elseif input_num == 1 disp(‘positive one’); else disp(‘other value’); end The use of the switch case allows the function to run more efficiently. NOTE FOR C PROGRAMMERS: Unlike in C, MATLAB’s switch does not “fall through”. That is, if the first case statement is TRUE, other case statements do not execute. Therefore, break statements are not used. 45

Loops the break statement Example (for loop): for t = 1:5000 y(t) = sin (2*pi*t/10); end Example (while loop): EPS = 1; while ( 1+EPS) >1 EPS = EPS/2; EPS = 2*EPS for loop for variable = expression commands end while loop while expression the break statement break – is used to terminate the execution of the loop.

All MATLAB commands are M-files. So far, we have discussed the execution of commands in the command window. But a more practical way is to create a M-file. The M-file is a text file that consists a group of MATLAB commands. MATLAB can open and execute the commands exactly as if they were entered at the MATLAB command window. To run the M-files, just type the file name in the command window. (make sure the current working directory is set correctly) All MATLAB commands are M-files.

User-Defined Function Add the following command in the beginning of your m-file: function [output variables] = function_name (input variables); NOTE: the function_name should be the same as your file name to avoid confusion. calling your function: -- a user-defined function is called by the name of the m-file, not the name given in the function definition. -- type in the m-file name like other pre-defined commands. Comments: -- The first few lines should be comments, as they will be displayed if help is requested for the function name. the first comment line is reference by the lookfor command.

Built-in MATLAB Functions result = function_name( input ); abs, sign log, log10, log2 exp sqrt sin, cos, tan asin, acos, atan max, min round, floor, ceil, fix mod, rem help elfun  help for elementary math functions

Getting Help For help type one of following commands in the command window: help – lists all the help topic help topic – provides help for the specified topic help command – provides help for the specified command help help – provides information on use of the help command helpwin – opens a separate help window for navigation lookfor keyword – Search all M-files for keyword