Manual 1 Matlab
Manual 1 Matlab
Contents
1. The MATLAB Desktop
1.1. Workspace Management........[2] 1.2. Command Window Management[2] 1.3 Command History Management....[2] 2. Variables in MATLAB....[3]
3. Mathematical Functions
3.1. Complex numbers......[3] 3.2. Trigonometric Functions....[4] 3.3. Exponential Functions...[4]
4. Vectors or Arrays
4.1. Declaring vectors..[5] 4.2. Operations on vectors....[5] 4.3. Plotting two vectors.[6] 4.4. Polynomials...[8]
5. Matrices
5.1. Declaring matrices......[10] 5.2. Operations on matrices...[11] 5.3. Some applications....[12]
6. Plotting
6.1. 2-D Plotting...[13] 6.2. 3-D Plotting...[14]
7. Symbolic Math
7.1. Declaration.....[14] 7.2. Operations on symbolic math..[14] 7.2.1. Solving & substitution........[14] 7.2.2. Differentiation.....[15] 7.2.3. Integration.......[15] 7.2.4. Laplace transform.........[15] 7.2.5. Fourier transform...[16] 7.2.6. Solving Differential Equations...[16]
8. Programming concepts:
8.1. Logical Operators.....[17] 8.2. Conditional statements.....[17] 8.3. Loops........[18] 8.4. Some useful instructions.........[19] 8.5. Functions in MATLAB............[20]
-1-
MATLAB-2007
Instruction who whos clear clear(y) clear y save file_name load file_name
Definition Displays variables in the workspace Displays variables in the workspace with more details Deletes MATLAB workspace (all variables) Deletes the variable named y Deletes the variable named y (another way) Saves workspace variables to a storage device (e.g. HDD) Loads workspace variables from a storage device (e.g. HDD)
1.2. Command Window Management clc x=1; UP & DOWN arrows Clears command window ; suppresses echo Recall previously executed commands
1.3. Command History Management Double clicking any command in the command history will execute it again.
Signals & Systems Lab.-Manual(1)
-2-
MATLAB-2007
2. Variables in MATLAB
Identification A=34 X=[1 2 3 4] Y=[1 2 3; 4 5 6; 7 8 9]; S=hello R=3+2i or R=3+2j 5*3/9+12 inf (1/0) pi eps Integer Vector Matrix String
Variable type
Complex number (both declarations are equivalent) The result will be stored in a variable called ans Infinity 3.14 or Very small number; tends to zero
Note: MATLAB is case sensitive. So, x=3 doesnt mean that X=3 as they arent equivalent.
3. Mathematical Functions
3.1. Complex numbers
Output Declaring a complex number s [3] real part of s [4] imaginary part of s [5] absolute value of s : (3) 2 + (4) 2 or the non-negative value of any number s [53.1301] radian angle of s : tan 1 (4 / 3) [a+jb] results in a complex number of a, b [3-4j] conjugate of s (real-j*imag.)
-3-
MATLAB-2007
3.2. Trigonometric Functions Y=sin(x) Y=cos(x) Y=tan(x) Y=sec(x) Y=csc(x) Y=cot(x) Y=asin(x) Y=acos(x) Y=atan(x) Y=asec(x) Y=acsc(x) Y=acot(x) Y=sinh(x) Y=cosh(x) Y=tanh(x) Y=sech(x) Y=csch(x) Y=coth(x) Y=asinh(x) Y=acosh(x) Y=atanh(x) Y=asech(x) Y=acsch(x) Y=acoth(x)
Adding a before function name gives the inverse function of the original one. Adding h after function name gives the hyperbolic function of the original one. For inverse hyperbolic add both a at the front and h at the end of the function name.
Function x^n exp(x) log10(x) log2(x) log(x) pow2(x) Nextpow2(x) sqrt(x) factorial(x)
Example
xn :
Exponential function: Log(x)/log(10) [base 10 logarithm]: Log(x)/log(2) [base 2 logarithm]: Ln (natural logarithm): 2^x: Produces n where 2^nx:
x
-4-
MATLAB-2007
4. Vectors or Arrays
4.1. Declaring vectors X=[1 5 9 -3 5] Y=0:0.1:5 Z=linspace(0,10,11) Z=logspace(0,10,11) 4.2. Operations on vectors x(7) x(5:9) x(6:end) x(6:length(x)) x(1:1:6) x(1:2:7) x(8:-3:1) x([1 2 4 9]) x x. [r,c]=size(x) sum(x) mean(x) length(x) find(x==2) P=find(x>4) G=x(P) P=find(x>4 & x<10) P=find(x==5 | x>=8) x==5 Sol=x==3 y=x^2 y=x.^2 Displays 7th element of the vector named x Displays 5th to 9th elements of x Displays elements from the 6th to the last one of x Displays elements 1,2,3,4,5, and 6 (step one) Displays elements 1,3,5, and 7 (step two) Display elements 8,5, and 2 (step down by three) Display elements 1st,2nd,4th, and 9th elements The transpose of x, with conjugate if x is complex The transpose of x without conjugation at all Returns: r = number of rows of the vector x c = number of columns of the vector x Adds all elements of the vector x The mean value of the vector x sum(x)/length(x) Number of elements in the vector x Returns the locations of the elements in x which are equal to 2 Returns the locations of the elements in x which are greater than 4 in a vector P of zeros and ones (T/F) G is formed of the elements in x that are greater than 4 Returns the locations of the elements in x which are greater than 4 and in the same time are less than 10 in a vector P Returns the locations of the elements in x which are equal to 5 or are greater than or equal to 8 in a vector P Asks MATLAB if x equals 5 or not. Answer is 1 if true and 0 if false. The same as (x==3) but the answer (0/1) is stored in Sol. Squaring the vector x; will lead to error due to dimensions Squaring the elements of the vector x; no care for dimensions. X=[element1
element2 element3 . ]
(start:step:end) (start, end, no. of points) linear space (start, end, no. of points)
[100 101 . . . 1010]
-5-
MATLAB-2007
4.3. Plotting two vectors To plot any two vectors, there are two techniques: First technique: You should be aware of the contents of one of the two vectors at least and the relation of the other one to the known vector. An example of that is: plotting the sinusoidal function; you may want to plot Y=sin(X), so you should be aware by either X or Y and then use the relation between them (sin or asin according to the known vector) to plot the relationship between them.
-6-
MATLAB-2007
Second technique: In this one, you dont know a specific relationship between the vectors. For example, if you would like to plot the average temperature of the months of the year to their order according to the following table: MONTH Temperature 1 17 2 19 3 22 4 24 5 27 6 30 7 34 8 35 9 31 10 26 11 23 12 20
Of course, you dont have a specific relation between the month order and the average temperature. So, you should use this way for plotting the two vectors. On the MATLAB command widow, write the following instructions: >> Month=[1:1:12]; >> Temperature=[ 17 19 22 24 27 30 34 35 31 26 23 20]; >> plot(Month,Temperature) %% try : >> stem(Month,Temperature)
Note the following: The plot instruction is used to draw the relationship between any two vectors such that the first input argument of the instruction is represented on the X-axis while the second input argument is represented on the Y-axis. There are many formats for the PLOT instruction, check them by typing >>help plot on the MATLAB command window. Also, there are other instructions for plotting such as the STEM instruction. So, try typing it instead of the plot instruction in the previous examples. Furthermore, check the formats of the STEM instruction by typing >>help stem on the MATLAB command window. In the example of temperature vs. month order, you may get a continuous curve that describes the relation between vectors by finding a function between them using what is called Curve Fitting which will be discussed later. More details will be illustrated in the Plotting section of this manual.
-7-
MATLAB-2007
4.4. Polynomials
Sometimes you need to write a polynomial, find its roots, multiply it by another one, divide it by another polynomial, differentiate it, integrate it, substitute by a value in it, put it in partial fractions form, or fit it to get a curve of specific order. Make full use of the following table for that purpose: P=[1 3 4 4 6] Q=[1 6 2]
C=poly([1 2 3]) conv(P,Q) [s,r]=deconv(P,Q) roots(P) polyder(P) polyval(P,3) polyint(P,2) polyfit(x,y,n) [z,p,k]=residue(Q,P)
P = x 4 + 3x 3 + 4 x 2 + 4 x + 6 Q = x 2 + 6x + 2 C = ( x 1)( x 2)( x 3) Multiply P*Q Divide P/Q, where P=s+r/Q Find the roots of P (put P=0 get x) Derivative of P Substitute in P by x=3 Integrate P with constant of integration =2 Fit x to y by a curve of degree n Partial fractions of Q/P: z=gains of the partial fractions terms (or zeros) p=poles of the partial fractions terms k=free term of the division
Example:
F (x) = x 4 x 3 7 x 2 + x + 6 G (x) = x 2 + 5x + 6
Calculate the value of F(3) and G(-1). Find the roots of F(x) and G(x). Find F(x)*G(x). Find F(x)/G(x). dF ( x) dG ( x) and . Get dx dx Get F ( x)dx and G ( x)dx setting the constant of integration to be equal to 2.
vii.
G ( x) . F ( x)
-8-
MATLAB-2007
Solution:
Using simple calculus: i. Substitute by x=3 in F(x) to get F(3) : F (3) = 3 4 33 7 3 2 + 3 + 6 = 0 Substitute by x=-1 in G(x) to get G(-1) : G (1) = (1) 2 + 5 (1) + 6 = 2
Solve the equation: F ( x ) = x 4 x 3 7 x 2 + x + 6 = 0 to get the roots of F(x) simply, you can write it as: ( x + 1)( x 1)( x + 2)( x 3) = 0 the roots are x=-1,1,-2,3. Also, solve the equation G ( x) = x 2 + 5 x + 6 = 0 to get the roots of G(x) Simply, you can write it as: G ( x) = ( x + 2)( x + 3) = 0 the roots are x=-2,-3.
ii.
iii.
F ( x) G ( x) = ( x 2 + 5 x + 6)( x 4 x 3 7 x 2 + x + 6)
= x 6 + 4 x 5 6 x 4 40 x 3 31x 2 + 36 x + 36
iv. Using long division we get:
48 x 96 F ( x) = ( x 2 6 x + 27) + 2 G ( x) x + 5x + 6
&
v.
dF ( x) = 4 x 3 3x 2 14 x + 1 dx
dG ( x) = 2x + 5 dx
vi.
G ( x)dx =
vii.
x 3 5x 2 x 3 5x 2 + + 6 x + const. = + + 6x + 2 3 2 3 2
3 ( ) 4 + ( 1) x 3 x 1
-9-
MATLAB-2007
>>F=[1 -1 -7 1 6]; >>G=[1 5 6]; >>polyval(F,3) >>polyval(G,-1) >>roots(F) >>roots(G) >>conv(F,G) >>[s,r]=deconv(F,G) >>polyder(F) >>polyder(G) >>polyint(F,2) >>polyint(G,2) >>[z,p,k]=residue(G,F)
5.Matrices
A 3*4 zeros matrix A 2*5 ones matrix A 4*4 identity (unity) matrix A 4*4 random matrix ranging from 0 to 1 A 4*4 magic matrix (sum of any row = sum of any column)
- 10 -
MATLAB-2007
- 11 -
MATLAB-2007
2 1 1 X 6 1 1 1 Y = 3 1 2 3 Z 9
X 2 1 1 6 Y = 1 1 1 3 Z 1 2 3 9
% or solution=a\b
Curve Fitting If you would like to draw a curve (of degree 2 for e.g.) to represent the relation between the month order and temperature (previously discussed), you should write on the MATLAB command window the following:
>>month=1:1:12; >>temp=[17 19 22 24 27 30 34 31 26 23 20]; >>n=2; curve fitting between month and temp by degree n=2 >>p=polyfit(month,temp,n); >>x=1:0.1:12; >>y=polyval(p,x); >>plot(month,temp,r,x,y,g)
- 12 -
MATLAB-2007
6. Plotting:
6.1. 2-D plotting:
First of all, lets define a vector x=[-,] and another two vectors y and z, where y=sin(x) and z=cos(x). Then, you can declare that to MATLAB as follws:
>> x=[-pi:pi/10:pi] >>y=sin(x); >>z=cos(x); >>w=100*cos(x)
Now, you can use this table to access the PLOT instruction in the form you are desired in. plot(x,y,ro:,x,z,b+-.) Plotting sin and cos functions by two different line formats legend(sin(\theta),cos(\theta)) Prints legend on the graph using symbolic theta title(My graph) Prints graph title xlabel(\theta) Prints x-axis label ylabel(\function) Prints y-axis label grid on / grid off Toggle grid on and off hold on / hold off The new plot doesnt replace the old one / the new plot replaces the old one H=axis Now H is a vector that contains the axis limits axis([-1 1 -2 4]) New axis limits for x and y respectively point=ginput(3) Let the user click on three points on the graph and store their locations in a matrix called point (its size =3*2). Every row would have one point(x,y) point =ginput Let the user click any number of times until pressing ENTER and store the locations of the clicked points in a matrix called point. plotyy(x,y,x,w) Creates plot with 2 y-axes for different scaled functions. subplot(235) Creates a 2*3 graph and set attention to the fifth one text(x1,y1,this point) Write the text this point at point (x1,y1) stairs(x,y) Draws the relation between x and y in ladder steps stem(x,y,--) Discretized form of the relation between x and y bar(x,y) Draws the relation in bars bar3(x,y) Draws the relation in 3-D bars
- 13 -
MATLAB-2007
7. Symbolic Math:
7.1. Declaration:
Until now, you couldnt deal with MATLAB using symbols such as differentiating the function F ( x) = x sin( x) with respect to x or integrating it, but you are used to deal with MATLAB using numerical quantities. In symbolic math, you will be able to do that. So, check the following table to use MATLAB in symbolic form. syms x y z a b c d s t F=5*sin(x)+x G=sin(x)/(cos(y)+2) H=a*x-b*y+z Defines some symbols Defining a symbolic function f(x) Two variable-symbolic function g(x,y) Five variable-symbolic function h(a,b,x,y,z)
Getting f(2). Getting g(3,y) substitute by x=3 in g(x,y). Solve f(x)=0 and get x as an expression of other parameters or return its value if f is of single variable. Solve h=0 with respect to z get z as an expression of other parameters or variables of h. Solving for x as a default variable. Solve two linear simultaneous equations Solve three linear simultaneous equations Gets the limit for f when x tends to infinity
- 14 -
MATLAB-2007
7.2.2. Differentiation
Differentiate function f with respect to its default variable n times Partial derivative of function g with respect to x (g/x) n times Partial derivative of function g with respect to y (g/y)n times
7.2.3. Integration
Integration with respect to x (the default variable of f) and neglecting the constant of integration Integration of g with respect to x : g ( x, y )dx Limited integration of f:
f ( x)dx
0
f ( x)dx
a
int(g,x,1,2)
int(g,y,a,b)
Its very useful to use MATLAB for getting the Laplace and inverse Laplace transforms directly without mathematical derivations and calculations and loosing a lot of time using the symbolic math as follows. syms t s laplace(sin(t)) 1 ilaplace( 3 ) s Ztrans & iztrans Defining t and s as a symbol Getting the laplace transform of the function sin(t)
Getting the inverse laplace transform of the function 1 s3 Gets the z-transform and inverse z-transform for discrete signals
- 15 -
MATLAB-2007
Defining t, n, and w as symbols Fourier transform of the function sin(2t) Inverse fourier transform of 1 Discrete time fast fourier transform
Sometimes you are required to solve the following differential equation for example:
..
y+ x y+ x 2 = 0 y (0) = 1
.
& y(0) = 0
So, you may use MATLAB for that purpose as follows: Dsolve( D 2 y + Dy x + x 2 ,Dy(0)=1,y(0)=0) Solve a differential equation Dsolve(Dy=x+y,Dx=2*x-y) Solving two simultaneous D.E. Pretty(ans) Gives you the form of the variable ans that can be written in your sheet
Note that: (t): Delta Function u(t): Step Function >> dirac(t) >> heaviside(t)
- 16 -
MATLAB-2007
8. Programming conepts:
8.1. Logical Operators:
The famous logical operators are:
AND: logical anding between any two variables. >> a=1; Example: >> b=0; >> c=and(a,b) OR:
logical oring between any two variables. >> a=0; Example: >> b=1; >> c=or(a,b) logical anding between any two variables. >> a=1; Example: >> b=0; >> c=xor(a,b)
xor:
The logical operators AND & OR can be represented by symbols directly as shown in the example below:
Example:
- 17 -
MATLAB-2007
8.3. Loops:
Looping is very famous in all programming languages. The most common loops are the for-loops and the while-loops. Lets start by the for-loop:
Initialization for the counter For condition_on_counter
. . .
changing the value of the counter
end
Its very common for you not to make an infinite loop, but I should remind you not to do so. If happened by error: press ctrl while pressing pause/break to break it.
. .
<<operations_on_the_counter>>
. end
Signals & Systems Lab.-Manual(1)
- 18 -
MATLAB-2007
input
disp
num2str
str2num
inline
fminsearch
fzero
dirac
heaviside
- 19 -
MATLAB-2007
Example:
Here is the format of a function that calculates the sum and the product of three input variables.
>> a=3;
Signals & Systems Lab.-Manual(1)
- 20 -
MATLAB-2007
>> ans = 12
Now try calling it using:
>> [x,y]=example_func(a,b,c)
The output will be:
>> x= 12 y= 60
It is clear that in the first case you didnt assign output arguments, so the first output only was calculated while in the second case both of them were assigned because of assigning the sum to the variable x and the product to the variable y. Note that you dont have limitations on the names of the function variables and the calling variables, i.e. it needs not to be the same names. To check the availability of your function name, use help your_func_name before creating it. You can add any help comments for your function by inserting the following line before the first line in by inserting the following line before the first line in your function (i.e. before the word function):
% This function calculates the sum and the product of three input arguments.
Then type :
- 21 -
MATLAB-2007
Note that: most of the MATLAB instructions that deal with vectors and matrices,
previously discussed, can do the same task with the symbolic forms.
MATLAB version:
M-files: you can use the MATLAB editor (M-file editor) instead of using the command
window as its more flexible to change any instructions or parameters in the editor of the M-file then save changes and re-run the code, to get it from the MATLAB toolbar: File New M file then save it and write your code or instructions.
Very important: dealing with MATLAB doesnt require full memorization of its
instructions and their formats, but you are preferred only to memorize the name of the instructions and then you may use the great help of MATLAB to know every thing about these instructions. Just write the following on the MATLAB command window:
Toolboxes: MATLAB has many great toolboxes which are simply a group of predefined
functions and blocks that may help in the field of engineering such as the Communication, Control, RF, toolboxes. Later on, we will focus on these toolboxes. For more details about these toolboxes, just type:
for e.g.:
Java & C++: MATLAB deals with Java and C++ efficiently, so you can switch between
them through a compiler that changes the code to the other programming method.
Text book: you can use the following text book as a reference for you:
Duane Hanselman(2001) Bruce Littlefield Mastering MATLAB 6 A Comprehensive Tutorial and Reference Prentice Hall, ISBN 0130194689
Visit: http://www.mathworks.com
Instructor:
- 22 -
MATLAB-2007