Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Introduction to MATLAB: Understanding Matrices, Functions, and Plotting, Study Guides, Projects, Research of Computer Science

An overview of matlab, a powerful tool for numerical computations, data visualization, and programming. Learn about the matlab desktop, variables, functions, matrices, and plotting. Discover how to use the editor, help system, and create matrices. Explore simple built-in functions and m-file functions.

Typology: Study Guides, Projects, Research

2018/2019

Uploaded on 11/16/2019

hmce-kalyani
hmce-kalyani 🇮🇳

1 document

1 / 13

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Signal and System Theory II, SS 2011 Prof. J. Lygeros
Automatic Control Laboratory
ETH Zurich, ETL I28
8092 Zurich
Introduction to MATLAB (Based on Matlab Manual)
1.1 What is MATLAB?
The name MATLAB stands for “MATrix LABoratory” and was originally designed as a tool for doing
numerical computations with matrices and vectors. It has since grown into a high-performance language
for technical computing. MATLAB, integrating computation, visualization, and programming in an easy-
to-use environment, allows easy matrix manipulation, plotting of functions and data, implementation of
algorithms, creation of user interfaces, and interfacing with programs in other languages. Typical uses
include:
Math and Computation
Modeling and Simulation
Data Analysis and Visualization
Application Development
Graphical User Interface development
1.2 Getting Started
1.2.1 Window Layout
The first time you start MATLAB, the desktop appears with the default layout, as shown in Figure 1.
The following tools are managed by the MATLAB desktop:
Command Window: Run MATLAB statements.
Current Directory Browser: To search for, view, open, find, and make changes to MATLAB
related directories and files, use the MATLAB Current Directory browser.
Command History: Displays a log of the functions you entered in the Command Window, copy
them, execute them, and more.
Workspace Browser: Shows the name of each variable, its value, and the Min and Max calcula-
tions, which MATLAB computes using the min and max functions, and updates automatically.
In case that the desktop does not appear with the default layout, you can change it by the menu
Desktop Desktop Layout Default.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Introduction to MATLAB: Understanding Matrices, Functions, and Plotting and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

Signal and System Theory II, SS 2011 Prof. J. Lygeros

Automatic Control Laboratory ETH Zurich, ETL I 8092 Zurich

Introduction to MATLAB (Based on Matlab Manual)

1.1 What is MATLAB?

The name MATLAB stands for “MATrix LABoratory” and was originally designed as a tool for doing numerical computations with matrices and vectors. It has since grown into a high-performance language for technical computing. MATLAB, integrating computation, visualization, and programming in an easy- to-use environment, allows easy matrix manipulation, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages. Typical uses include:

  • Math and Computation
  • Modeling and Simulation
  • Data Analysis and Visualization
  • Application Development
  • Graphical User Interface development

1.2 Getting Started

1.2.1 Window Layout

The first time you start MATLAB, the desktop appears with the default layout, as shown in Figure 1. The following tools are managed by the MATLAB desktop:

  • Command Window: Run MATLAB statements.
  • Current Directory Browser: To search for, view, open, find, and make changes to MATLAB related directories and files, use the MATLAB Current Directory browser.
  • Command History: Displays a log of the functions you entered in the Command Window, copy them, execute them, and more.
  • Workspace Browser: Shows the name of each variable, its value, and the Min and Max calcula- tions, which MATLAB computes using the min and max functions, and updates automatically.

In case that the desktop does not appear with the default layout, you can change it by the menu Desktop → Desktop Layout → Default.

View or change current Get Help Directory

View or Execute previously run commands from the Command History Window

Enter Matlab Functions at command line prompt

Use Tab to go to Workspace Browser

Click Start button for quick access to tools and more

Figure 1: Matlab Window (default layout)

1.2.2 Editor

MATLAB editor (Figure 2) can be used to create and debug M – files, which are programs you write to run MATLAB functions. A M – file is a text file that contains a sequence of MATLAB commands; the

for MATLAB: Command Line

  • HELP: HELP FUN displays a description of and syntax for the function FUN. (e.g. help plot)
  • DOC: DOC FUN displays the HTML documentation for the MATLAB function FUN. (e.g. doc help)

Help Browser Another source of help is the MATLAB help browser. You can invoke the MATLAB help browser by typing, helpbrowser, at the MATLAB command prompt, clicking on the help button, or by selecting Start → M AT LAB → Help from the MATLAB desktop.

1.3 Variables

The simplest way to use MATLAB is for arithmetic operations. The basic arithmetic operators are +, −, /, ∗ and ∧ (power). These operators can be used in conjunction with brackets (). As with all programming languages special care should be given on how a mathematic expression is written. For example, the result of the expression 5 + 10/ 2 ∗ 3 is 20 and corresponds in the expression 5 + (10/2) ∗ 3 and not in the expression 5 + 10/(2 ∗ 3). Generally, Matlab works according to the priorities:

(1) quantities in brackets

(2) powers

(3) ∗, / working left to right

(4) +, − working left to right

For example:

MATLAB always stores the result of a calculation in a varable named ans, but it is possible to use our own names to store numbers:

x=5+2^

x =

9

and then we can use these variables in other calculations:

y=2*x

y =

18

These are examples of assignment statements: values are assigned to variables. Each variable must be assigned a value before it may be used on the right of an assignment statement. One often does not want to see the result of intermediate calculations. This can be done by terminating the assignment statement or expression with semi–colon:

x=5+2^2; y=2*x; z=x^2+y^

z =

405

You can also assign pieces of text to variables, not just numbers. You do this using single quotes (not double quotes — single quotes and double quotes have different uses in MATLAB) around the text you want to assign to a variable. For example:

w = ’Goodmorning’; w

w =

Goodmorning

1.3.1 Variable Names

There are some specific rules for what you can name your variables, so you have to be careful.

  • Only use primary alphabetic characters (i.e., “A-Z”), numbers, and the underscore character in your variable names.
  • You cannot have any spaces in your variable names, so, for example, using “this is a variable” as a variable name is not allowed (in general, you can use the underscore character wherever you would use space to string words together in your variable name).
  • MATLAB is case sensitive. What this means for variables is that the same text, with different mixes of capital and small case letters, will not be the same variables in MATLAB. For example, “VaRIAbLe”, “variable”, “VARIABLE” and “variablE” would all be considered distinct variables in MATLAB.

1.4 Matlab Functions

1.4.1 Simple Built – in Functions

  • Trigonometric Functions:sin, cos, tan (their arguments should be in radians).
  • Inverse Trigonometric Functions:asin, acos, atan (the result is in radians).
  • Square root function:sqrt.
  • Exponential function:exp.

1.5.1 Creating Matrices in MATLAB

In MATLAB matrices are defined inside a pair of square brackets ([]). Punctuation marks of a comma (,), and semicolon (;) are used as a row separator and column separator, respectfully (you can also use a space as a row separator, and a carriage return (the enter key) as a column separator as well.). Use the examples below to check how vectors and matrices can be created in MATLAB.

A=[1,4,7]

B=[1;4;7]

C=[1 2 3;3 2 1;4 5 6;6 5 4]

You can also combine different vectors and matrices together to define a new matrix. For example:

D=[A A]

E=[B B]

F=[C C]

G=[C;C]

1.5.2 Colon Operator

The colon operator allows you to create an incremental vector of regularly spaced points by specifying startvalue : increment : stopvalue. Instead of an incremental value you can also specify a decrement as well. Check the examples:

A=[0:10:200] and >> B=[100:-10:-100]

1.5.3 Indexing Into a Matrix

Once a vector or a matrix is created you might needed to extract only a subset of the data, and this is done through indexing. Each element of a matrix is indexed according to which row and column it belongs to. The entry in the ith row and jth column is denoted mathematically by Ai,j and in Matlab by A(i, j). So for the matrix:

C=[1 2 3;4 5 6;7 8 9;10 11 12] the element in 3rd row and the 2nd column is:

C(3,2)

ans =

8

You can also extract any continuous subset of a matrix, by referring to the row range and column range you want. In the following examples we extract i) the 3rd column, ii) the 2nd and 3rd columns, iii) the 4th row, and iv) the central 2 × 2 matrix.

>> C(:,3)

>> C(:,2:3)

>> C(4,:)

>> C(2:3,2:3)

1.5.4 Matrix Operations

  • Addition: >> C = A + B
  • Subtraction: >> C = A − B
  • Multiplication: >> C = A ∗ B
  • Element-by-element Multiplication: C = A. ∗ B
  • Transposing: >> C = A′

Note: Matrices must have compatible dimensions.

1.5.5 Matrix Functions

  • The lu function expresses a matrix A as the product of two essentially triangular matrices, one of them a permutation of a lower triangular matrix and the other an upper triangular matrix. The factorization is often called the LU, or sometimes the LR, factorization. [L, U ] = lu(A) returns an upper triangular matrix in U and a permuted lower triangular matrix in L such that A = L ∗ U. Return value L is a product of lower triangular and permutation matrices.
  • The qr function performs the orthogonal-triangular decomposition of a matrix. This factorization is useful for both square and rectangular matrices. It expresses the matrix as the product of a real complex unitary matrix and an upper triangular matrix. [Q, R] = qr(A) produces an upper triangular matrix R of the same dimension as A and a unitary matrix Q so that A = Q ∗ R. For sparse matrices, Q is often nearly full. If [m n] = size(A), then Q is m × m and R is m × n.
  • [V, D] = eig(A) produces matrices of eigenvalues (D) and eigenvectors (V ) of matrix A, so that A ∗ V = V ∗ D. Matrix D is the canonical form of A a diagonal matrix with A’s eigenvalues on the main diagonal. Matrix V is the modal matrix its columns are the eigenvectors of A.
  • The svd command computes the matrix singular value decomposition. s = svd(X) returns a vector of singular values. [U, S, V ] = svd(X) produces a diagonal matrix S of the same dimension as X, with nonnegative diagonal elements in decreasing order, and unitary matrices U and V so that X = U ∗ S ∗ V ′.

1.6 Loops

There are occasions that we want to repeat a segment of code a number of different times. In such cases it is convenient to use loop structures. In MATLAB there are three loop structures:

  • For Loop The general syntax is:

x˙ = Ax + Bu y = Cx + Du

The output sys is an SS model that stores the model data.

1.7.2 Transfer Function

The function: sys = tf (num, den) creates a continuous-time transfer function with numerator and denominator specified by poly; with coefficients stored in the vectors num and den. The output sys is a TF object storing the transfer function data.

1.7.3 Convertions

  • tf 2 ss converts the parameters of a transfer function representation of a given system to those of an equivalent state-space representation. [A, B, C, D] = tf 2 ss(b, a) returns the A, B, C, and D matrices of a state space representation for the single-input transfer function

H(s) = B(s) A(s)

= C(sI − A)−^1 B + D (1)

  • ss 2 tf converts a state-space representation of a given system to an equivalent transfer function representation. [b, a] = ss 2 tf (A, B, C, D, iu) returns the transfer function

H(s) =

B(s) A(s)

= C(sI − A)−^1 B + D (2)

of the system

x˙ = Ax + Bu y = Cx + Du

from the iu-th input.

1.8 Model Simulation

The function lsim simulates the (time) response of continuous or discrete time linear systems (LTI) to arbitrary inputs. When invoked without left-hand arguments, lsim plots the response on the screen. Thus, lsim(sys, u, t) produces a plot of the time response of the LTI model sys to the input time history t, u. The vector t specifies the time samples for the simulation and consists of regularly spaced time samples.

t = 0 : dt : T f inal The matrix u must have as many rows as time samples (length(t)) and as many columns as system inputs. Each row u(i, :) specifies the input value(s) at the time sample t(i). When invoked with left-hand arguments, [y, t] = lsim(sys, u, t) [y, t, x] = lsim(sys, u, t) → for state-space models only [y, t, x] = lsim(sys, u, t, x0) → with initial state x 0 return the output response y, the time vector t used for simulation, and the state trajectories x (for state-space models only). There are also Matlab functions for specific type of inputs:

  • Step input: step(sys, t) or [y, t, x] = step(sys)
  • Impulse input: impulse(sys, t) or [y, t, x] = impulse(sys)

1.8.1 Ordinary Differential Equations Solver

In some cases, a model is described by a system of differential equations instead of a State Space or a Transfer Function. For such cases an odesolver can be used to calculate the system response. The most common syntax is: [T, Y ] = solver(odef un, tspan, y0) (where solver is one of ode45, ode23, ode113, ode15s, ode23s, ode23t, or ode23tb.) with tspan = [t 0 tf ] and integrates the system of differential equations y′^ = f (x, t) from time t 0 to tf with initial conditions y 0. odef un is a function handle. Function f = odef un(t, y), for a scalar t and a column vector y, must return a column vector f corresponding to f (x, t). Each row in the solution array Y corresponds to a time returned in column vector T. An odesolver can be used for example for the carrier pendulum shown in Figure 3. The code for this system and the Matlab Function (odefun) for the carrier pendulum differential equations are shown below.

clear all t_init=0;T_s=0.1;t_fin=40;options=[]; %simulation interval & sampling row_num=4; %state vector dimension x_system=zeros(row_num,ceil((t_fin-t_init)/T_s)); %system response cnt=1; %counter x_ode=zeros(row_num,1);x_ode(3)=50*pi/180; x_system(:,1)=x_ode; %initial conditions specifications for t=t_init:T_s:t_fin-T_s... cnt=cnt+1;... %counter increment F_l=0;... %input specification [t_ode,x_ode]=ode45(’carrierpendulum’,[t t+T_s],[x_ode],options,F_l);... szx_ode=size(x_ode);x_ode=x_ode(szx_ode(1),:)’;x_system(:,cnt)=x_ode;... end figure(1) t=[t_init:T_s:t_fin]; subplot(2,2,1),plot(t,x_system(1,:)),title(’carrier position’) subplot(2,2,2),plot(t,x_system(2,:)),title(’carrier velocity’) subplot(2,2,3),plot(t,x_system(3,:)),title(’pendulum angle’)

>> Y=3.*X;

plot(X,Y)

1.9.1 Multiple Plots and Subplots

Another thing you might want to do is superimpose multiple plots in the same figure window, to compare the plots for example. This can be done using the hold command. Normally, when you type a plot com- mand, any previous figure window is simply erased, and replaced by the results of the new plot. However, if you type “hold on” at the command prompt, all line plots created after that will be superimposed in the same figure window and axes. Likewise the command “hold off” will stop this behavior, and revert to the default (i.e., new plot will replace the previous plot). For example:

X=[1 3 4 6 8 12 18]; Y1=3.X; Y2=4.X+5; Y3=2.*X-3; plot(X,Y1); hold on plot(X,Y2); plot(X,Y3);

Still another thing you might want to do is to have multiple plots in the same window, but each in a separate part of the window (i.e., each with their own axes). You can do this using the subplot command. If you type subplot(M,N,P) at the command prompt, MATLAB will divide the plot window into a bunch of rectangles — there will be M rows and N columns of rectangles — and MATLAB will place the result of the next ”plot” command in the Pth rectangle (where the first rectangle is in the upper left). For example:

subplot(3,1,1) plot(X,Y1) subplot(3,1,2) plot(X,Y2) subplot(3,1,3) plot(X,Y3)