







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
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
1 / 13
This page cannot be seen from the preview
Don't miss anything!
Automatic Control Laboratory ETH Zurich, ETL I 8092 Zurich
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:
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:
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 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.
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.
1.4.1 Simple Built – in Functions
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.
1.5.4 Matrix Operations
Note: Matrices must have compatible dimensions.
1.5.5 Matrix Functions
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:
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
H(s) = B(s) A(s)
= C(sI − A)−^1 B + D (1)
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.
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:
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’)
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)