MATLAB
What is Matlab?
Is an interactive program for numerical computation and data visualization; it is used extensively by control engineers for analysis and design.
There are many different toolboxes available which extend the basic functions of Matlab into different application areas for example: Control Systems Toolbox.
MATLAB: stands for Matrix Laboratory How to represent Vectors
Enter each element of the vector (separated by a space) between brackets, and set it equal to a variable. As example:
a = [1 2 3]
Matlab should return:
a =
1 2 3 4 5 6 9 8 7
Colon Operator ( : )
The colon operator is powerful tool for creating and manipulating arrayssat If a colon is used to separate two numbers, MATLAB generates the number between them using an increment of one:
>> t=1:5
t= 1 2 3 4 5
If colons are used to separate three numbers MATLAB generates the number between first and third using an increment of second number:
>> t = 0:2:20
t = 0 2 4 6 8 10 12 14 16 18 20
Linspace and logspace functions
The linspace function generates a row vector of equally spaced points. It has the form Linspace(x1,x2,n)
Which gerates n points between x1 and x2
>>t=linspace (0,1,6) t=
0 0.2 0.4 0.6 0.8 1
If n is omitted the function automatically generates 100 points
The logspace function generates a row vector that is logarithmically equally spaced. It has the form:
Logspace(x1,x2,n)
Which generates n logarithmically spaced points between 10x1 and 10x2
>>y=logspace(-1,2,4) y=
0.1 1 10 100 Manipulating vectors:
First, suppose you would like to add 2 to each of the elements in vector 'a'. The equation for that looks like:
b = a + 2
b =
3 4 5 6 7 8 11 10 9
Second, Now suppose, you would like to add two vectors together. If the two vectors are the same length, it is easy. Simply add the two as shown below:
c =
4 6 8 10 12 14 20 18 16 Subtraction of vectors of the same length
d=a-b d=
-2 -2 -2 -2 -2 -2 -2 -2 -2 Expressions
Like most other programming languages, MATLAB provides mathematical expressions, but unlike most programming languages, these expressions involve entire matrices. The building blocks of expressions are:-
1- Variables: variable name consists of a letter followed by any number or letters, digits or underscores. Note that (A and a are not same variable)
2- Numbers: MATLAB uses conventional decimal notation, with an optional decimal point and leading plus or minus sign, for numbers. Scientific notation uses the letter e to specify a power-of-ten scale factor. Imaginary numbers use either i or j as a suffix. Some examples of legal numbers are
3 -99 0.0001 9.6397238 1.60210e-20 6.02252e23 1i -3.14159j 3e5i
3- Operators: Expressions use familiar arithmetic operators and precedence rules.
+ Addition - Subtraction * Multiplication / Division \ Left division
^ Power ' Complex conjugate transpose ( ) Specify evaluation order
4- Functions: MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, sin, cos, log, etc. Taking the square root or logarithm of a negative number is not an error; the appropriate complex result is produced automatically. MATLAB also provides many more advanced mathematical functions, including Bessel and gamma functions. Most of these functions accept complex arguments.
For a list of the elementary mathematical functions, type: help elfun
For a list of more advanced mathematical and matrix functions, type : help specfun or help elmat
Several special functions provide values of useful constants:-
pi 3.14159265 i Imaginary unit j Same as i inf Infinity NaN Not a number eps Floating point relative precision
realmin Smallest floating point number realmax Largest floating point number
Examples of Expressions
Mathematical Expression MATLAB representation x
x x
y = 2 +2π + y=x^2+2*pi*x+sqrt(x)
2 / ) 5 1
( + T
ρ = rho = (1+sqrt(5*t))/2
RT
p=ρ Pre=den*R*t
The format command
It control the numeric format of values displayed on the screen format short format short e format long format long e format rat M-files:
An m-file contains a series of statements that can be run all at once. Note that the nomenclature M-file comes from the fact that such file are stored with a .m extension. M- files come in two flavors: script files and function files
Script files: A script file is merely a series of MATLAB command that are saved on a file. The script can be executed by typing the file name in the command window or by invoking the menu selection in the edit window: Debug, Run.
Example:
Develop a script file to compute the velocity v where:
= t
m gc c
v gm d
d
tanh , take:
g=9.81, m=68.1, t=12, cd=0.25
Solution:
Open the editor with menu selection: File, New, M-file, type in the following statements to compute ‘v’:
M-file
g=input(‘value of g=’);
m=68.1;
t=12;
cd=0.25;
v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t)
Save the file as scriptdemo.m
Return to command window and type on it:
>> scriptdemo.m
The result will display as v=50.6175
Creating Functions
Matlab allows you to write your own functions with the function command:- Functions accept arguments and produces output. The general form of the function is:
function [output1,output2]= filename(input1,input2,input3)
function [var3] = add(var1,var2)
%add is a function that adds two numbers var3 = var1+var2;
If you save these three lines in a file called "add.m" in the Matlab directory, then you can use it by typing at the command line or in m-file: y = add(3,8)
function c=mf(a,b) c= sqrt(a.^2+b.^2)
Save these two lines in a file called "mf.m" in the Matlab directory, then you can use it by typing at the command line: t = mf(5,10)
Input – output
The input function allows you to prompt the user for values directly from the command window. Its syntax:
m=input(‘mass (kg) : ‘)
When the line is executed, the user is prompted with message mass (kg) : if the user enters a value, it would then be assigned to the variable m
The input function can also return user input as a string. To do this, an ‘s’ is appended to the function’s argument list. For example
Name=input(‘enter your name: ‘,’s’)
The disp function provides a handy way to display a value. Its syntax is Disp(value)
Where value=the value you like to display
Plotting
It is also easy to create plots in Matlab. Suppose you wanted to plot a sine wave as a function of time. First make a time vector (the semicolon after each statement tells Matlab we don't want to see all the values) and then compute the sin value at each time.
MATLAB program:
t=0:0.25:7;
y = sin(t);
plot(t,y)
note:
save this program as test.m
and execute it you get the result which on the right column
Example:
plot the simple, linear formula: y=3x
MATLAB program:
x = 0:0.1:100;
y = 3*x;
plot(x,y)
note:
Running the above m- file will generate the plot on the right
colnm.
Plot aesthetics: The color and point marker can be changed on a plot by adding a third parameter (in single quotes) to the plot command. For example, to plot the above function as a red, dotted line, the m-file should be changed to:
MATLAB program:
x = 0:0.1:100;
y = 3*x;
plot(x,y,'r:')
The plot now looks like:
The third input in plot function consists of one to three characters which specify a color and/or a point marker type. The list of colors and point markers is as follows:
y yellow . point m magenta o circle c cyan x x-mark r red + plus g green - solid b blue * star w white : dotted k black -. dashdot -- dashed
Plotting more than one function on the same figure: Let's say you want to plot a sine wave and cosine wave on the same set of axes, using a different color and point marker for each. The following m-file could be used to do this:
MATLAB program:
x =
linspace(0,2*pi,50);
y = sin(x);
z = cos(x);
plot(x,y,'r',x,z,'gx') note:
Running the above m-file will generate the plot on the right colnm.
By adding more sets of parameters to plot, you can plot as many different functions on the same figure as you want. When plotting many things on the same graph it is useful to differentiate the different functions based on color and point marker. This same effect
can also be achieved using the hold on and hold off commands. The same plot shown above could be generated using the following m-file:
x = linspace(0,2*pi,50);
y = sin(x);
plot(x,y,'r') z = cos(x);
hold on
plot(x,z,'gx') hold off
Subplotting: More than one plot can be put on the same figure using the subplot
command. The subplot command allows you to separate the figure into as many plots as desired, and put them all in one figure. To use this command, the following line of code is entered into the Matlab command window or an m-file:
subplot(m,n,p)
This command splits the figure into a matrix of m rows and n columns, thereby creating m*n plots on one figure. The p'th plot is selected as the currently active plot. For instance, suppose you want to see a sine wave, cosine wave, and tangent wave plotted on the same figure, but not on the same axis. The following m-file will accomplish this:
MATLAB program:
x =
linspace(0,2*pi,50);
y = sin(x);
z = cos(x);
w = tan(x);
subplot(2,2,1) plot(x,y)
subplot(2,2,2) plot(x,z)
subplot(2,2,3) plot(x,w) note:
Running the above m- file will generate the plot on the right colnm.
Changing the axis: Now you have found different ways to plot functions, you can
axis command. The axis command changes the axis of the plot shown, so only the part of the axis that is desirable is displayed. The axis command is used by entering the following command right after the plot command (or any command that has a plot as an output):
axis([xmin, xmax, ymin, ymax])
Examlpe:
For instance, suppose want to look at a plot of the function y=exp(5t)-1.
MATLAB program:
t=0:0.01:5;
y=exp(5*t)-1;
axis([0, 1, 0, 50]) plot(t,y)
note:
Running the above m-file will generate the plot on the right colnm.
Adding text: Another thing that may be important for your plots is labeling. You can give your plot a title (with the title command), x-axis label (with the xlabel command), y- axis label (with the ylabel command), and put text on the actual plot. All of the above commands are issued after the actual plot command has been issued.
A title will be placed, centered, above the plot with the command:
title('title string').
The x-axis label is issued with the following command:
xlabel('x-axis string') The y-axis label is issued with the following command:
ylabel('y-axis string')
Furthermore, text can be put on the plot itself in one of two ways: the text command and the gtext command. The first command involves knowing the coordinates of where you want the text string. The command is text(xcor,ycor,'textstring'). To use the other command, you do not need to know the exact coordinates. The command is gtext('textstring'), and then you just move the cross-hair to the desired
location with the mouse, and click on the position you want the text placed. To further demonstrate labeling, take the step response plot from above. Assuming that you have already changed the axis, copying the following lines of text after the axis command will put all the labels on the plot:
Example:
title('step response of something')
xlabel('time (sec)')
ylabel('position, velocity, or something like that') gtext('unnecessary labeling')
Other commands that can be used with the plot command are:
• clf (clears the current plot, so it is blank)
• figure (opens a new figure to plot on, so the previous figure is saved)
• close (closes the current figure window)
• loglog (same as plot, except both axes are log base 10 scale)
• semilogx (same as plot, except x-axis is log base 10 scale)
• semilogy (same as plot, except y-axis is log base 10 scale)
• grid (adds grid line to your plot)
3D plotting: When you make a 3-dimensional plot, you usually have a z-variable that is a function of both x and y. When you want x and y to vary over some range, you need a matrix (rather than a vector) for x and y to get a complete domain that covers all the different combinations of those x and y values over some range. A function called meshgrid will set up x and y matrixes like this for you. The x matrix varies the x down rows and keeps it constant in columns, and the y matrix varies the y in columns and keeps it constant across rows, so you get all combinations of x and y if you use the two matrices.
Example
To get a rectangular domain that goes from x=1 to x=10 in steps of .5, and from y=1 to y=10 in steps of .5 using meshgrid, Then, you can do a 3d plot by calculating some z values on the x and y domains, and doing a surface, mesh, or contour plot:
z = x.^2 - y.^2 surf(x,y,z) mesh(x,y,z) contour(x,y,z)
You could also use surfc or meshc to get surface or mesh plots with a contour plot drawn on the x-y plane. Surface plots and mesh plots color the plots according to the z value, by default. You can use some other equally-sized matrix to get the coloring instead by adding that matrix as an extra argument, like:
c = x.^2 + y.^2;
mesh(x,y,z,c)
Matrices
Entering matrices into Matlab is the same as entering a vector, except each row of elements is separated by a semicolon (;) or a return:
>>B = [1 2 3 4;5 6 7 8;9 10 11 12]
B =
1 2 3 4 5 6 7 8 9 10 11 12
>> B = [ 1 2 3 4 5 6 7 8 9 10 11 12]
B =
1 2 3 4 5 6 7 8 9 10 11 12
Matrices manipulation
1- Transpose of a matrix using the apostrophe key:
C = B' C =
1 5 9
2 6 10 3 7 11 4 8 12
It should be noted that if C had been complex, the apostrophe would have actually given the complex conjugate transpose. To get the transpose, use .' the two commands are the same if the matix is not complex).
2- Multiply the two matrices B and C together. Remember that order matters when multiplying matrices.
D = B * C
D =
30 70 110 70 174 278 110 278 446 D = C * B
D =
107 122 137 152 122 140 158 176 137 158 179 200 152 176 200 224
3- Multiply the corresponding elements of two matrices using the .* operator (the matrices must be the same size to do this).
E = [1 2;3 4];
F = [2 3;4 5];
G = E .* F
G =
2 6 12 20
If you have a square matrix, like E, you can also multiply it by itself as many times as you like by raising it to a given power.
E^3
ans =
37 54 81 118
E.^3
ans =
1 8 27 64 4- Inverse of a matrix:
X = inv(E)
X =
-2.0000 1.0000 1.5000 -0.5000 5- eigenvalues:
eig(E)
ans =
-0.3723 5.3723
6- Coefficients of the characteristic polynomial of a matrix: The "poly" function creates a vector that includes the coefficients of the characteristic polynomial.
p = poly(E) p =
1.0000 -5.0000 -2.0000
Remember that the eigenvalues of a matrix are the same as the roots of its characteristic polynomial:
roots(p)
ans =
5.3723 -0.3723 7- Identity matrix:
eye(m,n) returns m-by-n rectangular identity matrix
eye(n) returns n-by-n square identity matrix 8- Diagonal of matrix:
Diag( matrix name) 9- Determinant of matrix Det( matrix name)
10- Generating matrix which has zero elements zeros(n,m)
11- Generating matrix which has elements all equal one ones(n,m)
12- Deleting rows or columns
You can delete rows and columns from matrix using just a pair of square brackets
x=[1 2 5;3 4 1]
x(:,2)=[ ]
x=
1 5 3 1
13- Array operation
.* Element – by- element multiplication ./ Element – by- element division .\ Element – by- element left division .^ Element – by- element power .’ unconjugated array transpose Load function
Load function reads binary files containing matrices generated by earlier matlab sessions or read text files containing numeric data. Assume we have xxy.dat file which contains the following data:
5 1 2 6 3 4
>> load xxy.dat
>> xxy= 6 7 8 5 1 2 6 3 4
Tutorial (1)
1- Given q(t) as function of time t as:
−
= − t
L R e Lc
q t
q Rt L
2 2
0 2
cos 1 )
( use
MATLAB to generate a plot of this function from t=0 to 0.5. given that q0=10, R=50, L=5 and C=10-4.
2- The standard normal probability density function is a bell-shaped curve that can
be represented as: 2
2
2 ) 1
(z e z
f = −
π use MATLAB to generate a plot of this function from z=-3 to z=3 label the ordinate as frequency and the abscissa as z.
3- Use the linspace function to create vectors identical to the following created
with colon notation.
a- t=5:5:30 b- x=-3:3
4- If a force F(N) is applied to compress a spring, its displacement x(m) can often by Hooke’s law:F =Kx where K=the spring constant (N/m). the potential energy stored in the spring U(J) can be computed as: 2
2 1Kx
U = . six springs are tested and the following data compiled:
F(N) 10 12 15 9 12 16
X(m) 0.013 0.020 0.009 0.01 0.012 0.01
Use MATLAB to store F and x as vectors and the compute vectors of the spring constant and potential energies. Use the maximum function to determine the maximum potential energy.
5- Manning’s equation can be used to compute the velocity of water in a rectangular open channel:
23
2
= +
H B
BH n
U S where: U=velocity (m/s)
S=channel slope n=roughness coefficient B=width (m) and H=depth (m). the following data is available for five channels:
n S B H
0.035 0.0001 10 2
0.020 0.0002 8 1
0.015 0.0010 20 1.5
0.030 0.0007 24 3
0.022 0.0003 15 2.5
Store these values in a matrix where each row represents one of the channels and each column represents one of the parameters . write a single-line MATLAB statements to compute vector containing the velocities based on the values in the
6- Here is some wind tunnel data for force (F) versus velocity (v):
v (m/s) 10 20 30 40 50 60 70 80
F (N) 25 70 380 550 610 1220 830 1450
This data can be described by the following function: F=0.274v1.9842
Use Matlab to create a plot displaying both the data (using diamond symbol) and the function (using a dotted line). Plot the function for v=0 to 100 m/s
7-
8- A number of matrices are defined as:
= 6 5
2 1
5 4 ]
[A
=
4 0 1
6 2 1
7 3 4 ]
[B
= 1 6 2 ]
[C
=
5 7 1 2
6 3 4 ] 5
[D
=
5 0 4
3 1 7
6 5 1 ]
[E
=
3 6 1
1 0 ] 2
[F [G]=
[
8 6 4]
Perform the following operations:
(1) [E]+[B] (2) [B]-[E] (3) [A]+[F] (4) 5x[B] (5) [A]x[[B]
(6) [B]x[A] (7) [G]x[C] (8) [C]T (9) [D]T (10) Ix[B]
9-
10-
11-
12-
13-
14-
15-
16-
17-
18-
19-