Introduction to MATLAB 58:111 Numerical Calculations Department of Mechanical and Industrial Engineering.

Slides:



Advertisements
Similar presentations
Introduction to MATLAB
Advertisements

MATLAB – A Computational Methods By Rohit Khokher Department of Computer Science, Sharda University, Greater Noida, India MATLAB – A Computational Methods.
Introduction to Matlab
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.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB.
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
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 Fundamentals.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Programming in MATLAB ME 303. Outline of Lecture What is Matlab? Windows? Data Types –arrays: char, numeric, struct, cell Operators –arithmetic, relational,
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.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
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,
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
Introduction to MATLAB
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
How to Use MATLAB A Brief Introduction. 2 What can MATLAB do? Matrix Operations Symbolic Computations Simulations Programming 2D/3D Visualization.
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.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
INTRODUCTION TO MATLAB LAB# 01
Introduction to Matlab Module #2 Page 1 Introduction to Matlab Module #2 – Arrays Topics 1.Numeric arrays (creation, addressing, sizes) 2.Element-by-Element.
Introduction to Engineering MATLAB – 2 Introduction to MATLAB - 2 Agenda Defining Variables MATLAB Windows.
Peng Liu Haas School of Business University of California, Berkeley
MAE 1202: AEROSPACE PRACTICUM An Introduction to MATLAB: Part 2 Mechanical and Aerospace Engineering Department Florida Institute of Technology Developed.
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
Introduction to MATLAB. CSPP58001 MATLAB MATLAB is is a matrix-based language well suited for carrying out numerical analysis. It has many, many high-
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
OUTLINE Overview Numbers, variables and similar in Matlab
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Master in Optical Fiber Communications and Photonic Technologies Foundations of Digital Transmission - Fall quarter Introduction to Matlab.
1 DKT 211 Basic Communication Engineering LAB # 1A : (Lecture 1) Introduction to Matlab  Basic Features  Scientific features  Array Operations  Script.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB Lecture 18.
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.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
1 Lecture 1 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
Part 1 Chapter 2 MATLAB Fundamentals PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and Prof. Steve Chapra, Tufts University All.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
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.
1 Lecture 3 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
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.
Introduction to MATLAB Ehsan Adeli M. Iran University of Science and Technology, E-Learing Center, Fall 2008 (1387)
CS100A, Fall 1998, Lecture 191 CS100A, Fall 1998 Lecture 19, Thursday Nov 05 Matlab Concepts: Matlab arrays Matlab subscripting Matlab plotting.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
Tutorial on Matlab Basics
ECE 1304 Introduction to Electrical and Computer Engineering
MATLAB DENC 2533 ECADD LAB 9.
Introduction To MATLAB
Use of Mathematics using Technology (Maltlab)
Communication and Coding Theory Lab(CS491)
Experiment No. (1) - an introduction to MATLAB
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Presentation transcript:

Introduction to MATLAB 58:111 Numerical Calculations Department of Mechanical and Industrial Engineering

Topics Introduction Running MATLAB and MATLAB Environment Getting help Variables Vectors, Matrices, and linear Algebra Mathematical Functions and Applications Plotting Programming M-files User Defined Functions

Introduction What is MATLAB MATLAB, which stands for MATrix LABoratory, is a powerful program that combines computation and visualization capability for science and engineering simulations. MATLAB provides the user: Manage variables Import and export data Perform calculations Generate Plots …………..

Running MATLAB To run MATLAB: Login any ICAEN PC with WIN XP Start -> All Programs -> Engineering Software -> MATLAB 7.0

Main Working Windows After the “>>” symbol, you can type the commands

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

Getting Help To get help: MATLAB main menu -> Help -> MATLAB Help

Getting Help Type one of the following commands in the command window: help – lists all the help topics help topic – provides help for the specified topic help command – provides help for the specified command helpwin – opens a separate help window for navigation Lookfor keyword – search all M-files for keyword Online resource

Variables Variable names: Must start with a letter. May contain only letters, digits, and the underscore “_”. MATLAB is case sensitive, for example one & ONE are different variables. MATLAB only recognizes the first 31 characters in a variable name. Assignment statement: Variable = number; Variable = expression; Example: >> t = 1234; >> t = 1234 t = 1234

Variables Special variables: ans: default variable name for the result. pi: π = …… eps: ε= e-016, smallest value by which two numbers can differ inf: ∞, infinity NAN or nan: not-a-number Commands involving variables: who: lists the names of the defined variables whos: lists the names and sizes of defined variables clear: clears all variables clear name: clears the variable name clc: clears the command window clf: clears the current figure and the graph window

Vectors 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 = [ *pi 0.5*pi 0.75*pi pi] x = x is a row vector y=[0; 0.25*pi; 0.5*pi; 0.75*pi; pi] y = y is a column vector

Vectors Vector Addressing - A vector element is addressed in MATLAB with an integer index enclosed in parentheses. Example: >> x(3) ans = <- 3 rd element of vector X The colon notation may be used to address a block of elements (start:increment:end) Example: >> x(1:2:5) ans =

Vectors Some useful commands: x = start:end Create row vector x starting with start, counting by 1, ending at end x = start:increment:end Create row vector x starting with start, counting by increment, ending at or before end x = linspace(start,end,number) Create linearly spaced row vector x starting with start, ending at end, having number elements x = logspace(start,end,number) Create logarithmically spaced row vector x starting with start, ending with end, having number elements length(x)Returns the length of vector x y = x’Transpose of vector x dot(x,y),cross(x,y) Returns the scalar dot and vector cross product of the vector x and y

Array Operations Scalar-Array Mathematics For addition, subtraction, multiplication, and division of an array by a scalar, simply apply the operation to all elements of the array Example: >> f = [1 2; 3 4] f = >> g = pi * f / g =

Array Operations Element-by-Element Array-Array Mathematics Example: >> x = [1 2 3]; >> y = [4 5 6]; >> z = x.* y z = operationAlgebraic FormMATLAB Additiona + b Subtractiona – b Multiplication a  b a.* b Division a  b a./ b Exponentiationabab a.^ b

Matrices A matrix array is two-dimensional, having both mulitple rows and multiple columns. It begins with [, and end with ] Spaces or commas are used to separate elements in a row Semicolon or enter is used to separate rows Example: >> f = [1 2 3; 4 5 6] f = >> h = [ ] h =

Matrices Matrix Addressing: Matrix name(row,column) Colon maybe used in place of a row or column reference to select the entire row or column. Example: >> f(2,3) ans = 6 >> h(:,1) ans = 2 1

Matrices Some useful commands: zeros(n)Returns a n X n matrix of zeros zeros(m,n)Returns a m X n matrix of zeros ones(n)Returns a n X n matrix of ones ones(m,n)Returns a m X n matrix of ones size(A) For a m X n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix length(A)Returns the larger of the number of rows or columns in A

Matrices More commands: TransposeB=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 SubtractionC =A +B C =A - B Scalar MultiplicationB = α A, where α is a scalar Matrix MultiplicationC = A * B Matrix InverseB = inv(A), A must be a square matrix in this case Matrix powersB = A * A, A must be a square matrix Determinantdet(A), A must be a square matrix

Linear Equations Example: a system of 3 linear equations with 3 unknowns (x 1, x 2, x 3 ) 3 x 1 + 2x 2 - x 3 = 10 - x 1 + 3x 2 + 2x 3 = 5 x 1 - 2x 2 - x 3 = -1 Let: Then, the system can be described as: Ax = b

Linear Equations Solution by Matrix Inverse: Ax = b A -1 Ax = A -1 b Ax = b MATLAB: >> A = [3 2 -1; ; ]; >> b = [10;5;-1]; >> x = inv(A)*b x = Solution by Matrix Division: Ax = b Can be solved by left division b  A MATLAB: >> A = [3 2 -1; ; ]; >> b = [10;5;-1]; >> x =A \ b x =

Polynomials The polynomials are represented by their coefficients in MATLAB Consider the following polynomial: For s is scalar: use scalar operations A = s ^ * s ^ * s + 1; For s is a vector or a matrix: use array or element by element operation A = s.^ * s.^ * s + 1; Function polyval(a,s): evaluate a polynomial with coefficients in vector a for the values in s

Polynomials MATLAB: >> s = linspace(-5,5,100); >> coeff = [ ]; >> A = polyval(coeff,s); >> plot(s,A) >> xlabel('s') >> ylabel('A(s)')

Polynomials OperationMATLAB Command Description Additionc = a + bSum of polynomial A and B, the coefficient vectors must have the same length. Scalar Multipleb = 3 * aMultiply the polynomial A by 3. Polynomial Multiplication c = conv(a, b)Returns the coefficient vector for the resulting from the product of polynomial A and B. Polynomial Division [q,r] = deconv(a,b)Returns the long division of A and B. q is the quotient polynomial coefficient, and r is the remainder polynomial coefficient. Derivativespolyder(a) polyder(a,b) [n,d] = polyder(b,a) Returns the coefficients of the derivative of the polynomial A. Returns the coefficients of the derivative of the product of A and B. Returns the derivative of ratio B/A, represented as N/D. Find Rootsroots(a)Returns the roots of the polynomial A in column vector form. Find PolynomialsPoly(r)Returns the coefficient vector of the polynomial having roots r

Plotting For more information on 2-D plotting, type help graph2d Plotting a point: >>plot (variablename, ‘symbol’) Example: Complex variable >>z = j; >>plot(z,‘*') Commands for axes: CommandDescription axis([xmin xmax ymin ymax])Define minimum and maximum values of the axes axis squareProduce a square plot axis equalEqual scaling factors for both axes axis normalTurn off axis square, equal axis (auto)Return the axis to defaults

Plotting Plotting curves: plot(x,y) – generate a linear plot of the values of x (horizontal axis) and y (vertical axis) semilogx(x,y) - generate a plot of the values of x (logarithmic scale) and y (linear scale) semilogy(x,y) - loglog(x,y) - generate a plot of the values of x and y (both logarithmic scale) Multiple curves plot(x,y,w,z) – multiple curves can be plotted on the same graph: y vs. x and z vs. w legend(‘string1’,’string2’, …) – used to distinguish between plots on the same graph Multiple figures figure(n) – use in creation of multiple plot windows before the command plot() close – closes the figure n window close all – closes all the plot windows Subplots: subplot(m,n,p) – m by n grid of windows, with p specifying the current plot as the pth window

Plotting Example: (polynomial function) Plot the polynomial using linear/linear, log/linear, linear/log, log/log scale >>% generate te polynomial: >>x=linspace(0,10,100); >>y=2*x.^2+7*x+9; >>% plotting the polynomial: >>figure(1); >>subplot(2,2,1),plot(x,y); >>title('polynomial, linear/linear scale'); >>ylabel('y'),grid; >>subplot(2,2,2),semilogx(x,y); >>title('polynomial, log/linear scale'); >>ylabel('y'),grid; >>subplot(2,2,3),semilogy(x,y); >>title('polynomial, linear/log scale'); >>ylabel('y'),grid; >>subplot(2,2,4),loglog(x,y); >>title('polynomial, log/log scale'); >>ylabel('y'),grid;

Plotting

Adding new curves to the exsiting graph Use the hold command to add lines/points to an existing plot hold on – retain existing axes, add new curves to current axes. hold off – release the current figure windows for new plots Grids and labels: CommandDescription grid onAdd dashed grids lines at the tick marks grid offRemoves grid lines (default) GridToggles grid status (off to on or on to off) title(‘text’)Labels top of plot with text xlabel(‘text’)Labels horizontal (x) axis with text ylabel(‘text’)Labels vertical (y) axis with text text(x,y,’text’)Adds text to location (x,y) on the current axes, where (x,y) is in units from the current plot

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

Programming The switch statement: switch expression case test expression 1 commands case test expression 2 commands otherwise commands end Example: switch interval case 1 xinc = interval/10; case 0 xinc = 0.1; otherwise disp(‘wrong value’); end

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

M-Files Before, we have executed the commands in the command window. The more general 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)

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.

User-Defined Function Example ( circle1.m) function y = circle1(center,radius,nop,style) % circle1 draws a circle with center defined as a vector 'center' % radius as a scalar 'radius'. 'nop' is the number of points on the circle % 'style' is the style of the point. % Example to use: circle1([1 3],4,500, ':'); [m,n] = size(center); if (~((m == 1) | (n == 1)) | (m == 1 & n == 1)) error('Input must be a vector') end close all x0=center(1); y0=center(2); t0=2*pi/nop; axis equal axis([x0-radius-1 x0+radius+1 y0-radius-1 y0+radius+1]) hold on for i=1:nop+1 pos1=radius*cos(t0*(i-1))+x0; pos2=radius*sin(t0*(i-1))+y0; plot(pos1,pos2,style); end

User-Defined Function In command window: >> help circle1 circle1 draws a circle with center defined as a vector 'center' radius as a scalar 'radius'. 'nop' is the number of points on the circle 'style' is the style of the point Example to use: circle1([1 3],4,500,':'); Example: plot a circle with center (3,1), radius 5 using 500 points and style '--': >> circle1([3 1],5,500,'--'); Result in the Figure window