How to Use MATLAB A Brief Introduction. 2 What can MATLAB do? Matrix Operations Symbolic Computations Simulations Programming 2D/3D Visualization.

Slides:



Advertisements
Similar presentations
Introduction to MATLAB
Advertisements

Plotting Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to Matlab
Matlab Graphics S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: 2D Graphics.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
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 MECH 300H Spring Starting of MATLAB.
Introduction to MATLAB
EGR 106 – Week 3 – More on Arrays Brief review of last week Additional ideas: – Special arrays – Changing an array – Some array operators – Character arrays.
Matlab intro The Environment
Part 1 Chapter 2 MATLAB Fundamentals
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.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
1 Introduction to MATLAB MATLAB is all of the following: 1.Computational environment 2.Plotting software 3.Programming language Typical applications: 1.Calculations.
Programming in MATLAB ME 303. Outline of Lecture What is Matlab? Windows? Data Types –arrays: char, numeric, struct, cell Operators –arithmetic, relational,
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
What is Matlab? A software environment for interactive numerical computations Examples: –Matrix computations and linear algebra –Solving nonlinear equations.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Introduction to MATLAB D. Heslop and M. Schulz. Why MATLAB? If calculations have to be repeated many times  a computer is the ideal tool for such boring.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
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
Introduction to MATLAB 58:111 Numerical Calculations Department of Mechanical and Industrial Engineering.
CSE123 Lecture 5 Arrays and Array Operations. Definitions Scalars: Variables that represent single numbers. Note that complex numbers are also scalars,
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.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
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.
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.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
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.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
>> x = [ ]; y = 2*x y = Arrays x and y are one dimensional arrays called vectors. In MATLAB all variables are arrays. They allow functions.
Part 1 Chapter 2 MATLAB Fundamentals PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and Prof. Steve Chapra, Tufts University All.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
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 5 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
ECE 351 M ATLAB I NTRODUCTION ( BY T EACHING A SSISTANTS )
1 Lecture 3 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
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.
How to use MATLAB (using M-files) Double click this icon To start Matlab 6.5.
Tutorial on Matlab Basics
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,
Matrices and Arrays.
MATLAB DENC 2533 ECADD LAB 9.
Introduction To MATLAB
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files)
INTRODUCTION TO MATLAB
Plotting Signals in MATLAB
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Presentation transcript:

How to Use MATLAB A Brief Introduction

2 What can MATLAB do? Matrix Operations Symbolic Computations Simulations Programming 2D/3D Visualization

3 MATLAB Working Environments

4 Some Useful Commands help % list all the topics helpwin % display helping document by topics helpdesk% display helping document from the start page help command % display information of command type command% display brief information of command doc command% display document on command lookfor keyword% look for the commands related to keyword Ctrl + C% stop the running command quit or exit% quit and close MATLAB clear% remove all the data in current session ; (semicolon)% prevent commands from output results % (percent sign)% comments line

5 Variables Special variables: ans : default variable name for the result pi:  = ………… eps:  = e-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 variables, 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.

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

7 Vectors (con’t…) Vector Addressing – A vector element is addressed in MATLAB with an integer index enclosed in parentheses. Example: >> x(3) ans =  1 st to 3 rd elements 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 = NOTE: MATLAB index starts at 1.  3 rd element of vector x

8 Vectors (con’t…) 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 linspace(start,end,number) create row vector x starting with start, ending at end, having number elements 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.

9 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 = >> g = 2*f – 1 g = Each element in the array f is multiplied by 2, then subtracted by 1.

10 Array Operations (con’t…) Element-by-Element Array-Array Mathematics. OperationAlgebraic FormMATLAB Additiona + b Subtractiona – b Multiplicationa x ba.* b Division a  b a./ b Exponentiationabab a.^ b Example: >> x = [ ]; >> y = [ ]; >> z = x.* y z = Each element in x is multiplied by the corresponding element in y.

11 Matrices A is an m x n matrix.  A Matrix array is two-dimensional, having both multiple rows and multiple columns, similar to vector arrays:  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 = the main diagonal

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

13 Matrices (con’t…) Some useful commands: zeros(n) zeros(m,n) ones(n) ones(m,n) size (A) length(A) returns a n x n matrix of zeros returns a m x n matrix of zeros returns a n x n matrix of ones returns a m x n matrix of ones for a m x n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix. returns the larger of the number of rows or columns in A.

14 Matrices (con’t…) TransposeB = A’ Identity Matrixeye(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 Multiplication B =  A, where  is a scalar. Matrix MultiplicationC = A*B Matrix InverseB = inv(A), A must be a square matrix in this case. rank (A)  returns the rank of the matrix A. Matrix PowersB = A.^2  squares each element in the matrix C = A * A  computes A*A, and A must be a square matrix. Determinantdet (A), and A must be a square matrix. more commands A, B, C are matrices, and m, n,  are scalars.

15 Plotting For more information on 2-D plotting, type help graph2d Plotting a point: >> plot ( variablename, ‘symbol’)  Example : Complex number >> 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

16 Plotting (con’t…) Plotting Curves: plot (x,y) – generates 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 and y using a logarithmic scale for x and a linear scale for y semilogy (x,y) – generate a plot of the values of x and y using a linear scale for x and a logarithmic scale for y. loglog(x,y) – generate a plot of the values of x and y using logarithmic scales for both x and y Multiple Curves: plot (x, y, w, z) – multiple curves can be plotted on the same graph by using multiple arguments in a plot command. The variables x, y, w, and z are vectors. Two curves will be plotted: y vs. x, and z vs. w. legend (‘string1’, ‘string2’,…) – used to distinguish between plots on the same graph exercise: type help legend to learn more on this command. Multiple Figures: figure (n) – used in creation of multiple plot windows. place this command before the plot() command, and the corresponding figure will be labeled as “Figure n” close – closes the figure n window. close all – closes all the figure windows. Subplots: subplot (m, n, p) – m by n grid of windows, with p specifying the current plot as the p th window

17 Plotting (con’t…) Example: (polynomial function) plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, & log/log scale: y = 2x 2 + 7x + 9 % Generate the 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'); xlabel('x'), ylabel ('y'), grid; subplot (2,2,4), loglog (x,y); title ('Polynomial, log/log scale'); xlabel('x'), ylabel ('y'), grid;

18 Plotting (con’t…)

19 Plotting (con’t…) Adding new curves to the existing graph: Use the hold command to add lines/points to an existing plot. hold on – retain existing axes, add new curves to current axes. Axes are rescaled when necessary. hold off – release the current figure window for new plots Grids and Labels: CommandDescription grid onAdds 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 in quotes xlabel (‘text’)labels horizontal (x) axis with text is quotes ylabel (‘text’)labels vertical (y) axis with text is quotes text (x,y,’text’)Adds text in quotes to location (x,y) on the current axes, where (x,y) is in units from the current plot.

20 Additional commands for plotting SymbolColor yyellow mmagenta ccyan rred ggreen bblue wwhite kblack SymbolMarker.  o  x  ++ *  s □ d ◊ v  ^  hhexagram color of the point or curve Marker of the data pointsPlot line styles SymbolLine Style –solid line :dotted line –.dash-dot line – dashed line

21 Flow Control 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 (‘Below desired operating range.’) else disp (‘Too cold – turn off equipment.’) end

22 Flow Control (con’t…) The switch statement: switch expression case test expression 1 commands case test expression 2 commands otherwise commands end Example: switch interval < 1 case 1 xinc = interval /10; case 0 xinc = 0.1; end

23 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): EPS = 1; while ( 1+EPS) >1 EPS = EPS/2; end EPS = 2*EPS the break statement break – is used to terminate the execution of the loop.

24 M-Files 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. So far, we have executed the commands in the command window. But a more practical way is to create a M-file.

25 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.

26 Random Variable v=25; %variance m=10;%mean x=sqrt(v)*randn(1, 1000) + m*ones(1, 1000); figure; plot (x); grid; xlabel ('Sample Index'); ylabel ('Amplitude'); title ('One thousands samples of a Gaussian random variable(mean=10, standard deviation=5)');

27 Exp2-Random Variable

Thanks! More Info on MATLAB