MATLAB Tutorial Notes

20
Condensed Guide of Using MATLAB Navid Mostoufi Univerity of Tehran

Transcript of MATLAB Tutorial Notes

Page 1: MATLAB Tutorial Notes

Condensed Guide of Using MATLAB

Navid Mostoufi

Univerity of Tehran

Page 2: MATLAB Tutorial Notes

1

This pamphlet is prepared such that you should type commands in MATLAB environment and follow the results on the screen. The sign ">>" indicates MATLAB command line in which you type commands and you do not need to type it.

Basic operations Arrays can contain either numbers or letters. There are 4 types of arrays in MATLAB:

- Scalar: contains only one element (no dimension). - Vector: is a column or row of sevral elements (one dimension). - Matrix: in which elements are arranged in a rectangular fashion (two

dimensions). - Arrays with more than two dmensions.

When you assign a value to a variable, you see the result on the screen. If you want to avoide this, you should type semicolon after the operation: >> a=2.5 a = 2.5000 >> a=3.2; >> a a = 3.2000 >> p='hello' p = hello MATLAB is case sensitive: >> A ??? Undefined function or variable 'A'. Let’s define few vectors:

>> v=[1 2 3] v = 1 2 3 >> w=['abcd' '1234'] w = abcd1234 And some matrices: >> m=[1 2 3 4 5 6] m = 1 2 3 4 5 6

Page 3: MATLAB Tutorial Notes

2

>> n=['abcd' '1234'] n = abcd 1234 Elements of a matrix can be individually recalled or replaced:

>> m(2,3) ans = 6 >> m(2,3)=7 m = 1 2 3 4 5 7 Simple algebraic operations on vectors and matices can be carried out as follows:

>> 2*m ans = 2 4 6 8 10 14 >> m+1 ans = 2 3 4 5 6 8 >> n1=[2 5 4 -1 -2 0]; >> m+n1 ans = 3 7 7 3 3 7 Separating elements of a matrix in a row can be marked by a comma (,). Using a semicolon means moving to the next row: >> q=[1, 2, 3 4 5 6; 7 8 9] q = 1 2 3 4 5 6 7 8 9 Colon (:) has many applications in MATLAB. It can be used for addressing a row, a column or a part of a matrix:

Page 4: MATLAB Tutorial Notes

3

>> q(1,:) ans = 1 2 3 >> q(:,2) ans = 2 5 8 >> q(1:2,2:end) ans = 2 3 5 6

There is a simple way in MATLAB to generate a vector with equally spaced elements. Consider t is a vector whos first element is 0, its last element is 2 and all elements are 0.5 apart from each other. This vector can be generated as follows: >> t=0:.5:2 t = 0 0.5000 1.0000 1.5000 2.0000 Use the command “length” to obtain the number of elements in a vector: >> length(t) ans = 5 The command “size” reveals number of rows and columns of a matrix: >> size(n) ans = 2 4 Some useful functions that can be used for generating arrays are as follows:

Generates a 22 matrix of 1s ones(2) Generates a 23 matrix of 1s ones(2,3) Generates a 22 matrix of 0s zeros(2) Generates a 33 identity matrix eye(3) Generates a row vector of 7 linearly equally spaced points between -1 and 5

linspace(-1,5,7)

Generates a row vector of 8 logarithmically equally spaced points between decades 10^-1 and 10^2

linspace(-1,2,8)

Some useful functions that act on matrices:

The sum of the elements of the vector x sum(x) Product of elements prod(x) Largest component max(x) Smallest component min (x)

Page 5: MATLAB Tutorial Notes

4

Sort in ascending or descending order sort(x) Average or mean value mean(x) Standard deviation std(x)

Matrix operations Algebraic operations can be performed on arrays in either matrix form or element-by-element form. Algenraic operations in the matrix form obey the same rules as those in linear algebra. Transpose of a matrix is obtained using the prime symbol: >> r=rand(2,4) r = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185 >> r' ans = 0.9501 0.2311 0.6068 0.4860 0.8913 0.7621 0.4565 0.0185 Multiplication, addition and subtraction of matrices are done using the corresponding operator:

>> v=[1:4]; >> r*v' ans = 6.6636 3.5634 >> s=[0:3; 2:-.5:.5]; >> s+r ans = 0.9501 1.6068 2.8913 3.4565 2.2311 1.9860 1.7621 0.5185 Some useful matrix functions are listed below:

Determinant of the square matrix a det(a) Inverse of the square matrix a inv(a) Eigenvalues and eigenvectors eig(a)

Element-by-element operations This type of operation is completely different than those in the matrix operations. It is important to know the difference between these two operations and use the correct one in your programs since this difference may cause many calculation problems. Consider the following two vectors:

Page 6: MATLAB Tutorial Notes

5

>> a=[1 2 3]; >> b=[2 -1 0]; If you try to multiply these two vectors, using the conventional multiplication sign, you get the following error message: >> a*b ??? Error using ==> * Inner matrix dimensions must agree. The reason for getting such an error message is that in the linear algebra, multiplication of two matices is possible only if number of columns of the first matrix is equal to number of rows of the second one, which is not the case here. Now consider that we just want to multiply each element of matrix a by the corresponding element of matrix b. For this purpose, it is suuficient to put a point before the multiplication sign: >> a.*b ans = 2 -2 0 The same can be done for power or division. For example: >> a.^2 ans = 1 4 9 If you forget the point before the power symbol, you will get the following error message: >> a^2 ??? Error using ==> ^ Matrix must be square.

Polynomials Polynomials are defined in MATLAB with a row vector whose elemensts are coefficients of the polynomial in a decending order. For example, the polynomial p(x)=x3-2x+5 is represented by: >> p=[1 0 -2 5]; Roots of a polynomial can be obtained as follows: >> r=roots(p) r = -2.0946 1.0473 + 1.1359i 1.0473 - 1.1359i

Page 7: MATLAB Tutorial Notes

6

Knowing the roots, the polynomial can be obtained:

>> p2=poly([1 -1]) p2 = 1 0 -1 The function “polyval’ evaluates the polynomial value at the specified point(s):

>> polyval(p,5) ans = 120 Some useful functions about polynomials are as follows:

Polynomial multiplication conv(a,b) Polynomial division deconv(a,b) Differentiate polynomial polyder(a) Integrate polynomial analytically polyint(a,k)

Polynomial curve fitting The function polyfit finds the coefficients of a polynomial that best fits the given data by the least-squares technique. For example, consider the following set of data: >> x=[1 2 3 4 5]; >> y=[5.5 43.1 128 290.7 498.4]; The following statement determines the coefficients of a thord degree polynomial that best fits these data: >> p=polyfit(x,y,3) p = -0.1917 31.5821 -60.3262 35.3400 Now let’s see both data and the fitted curve together in order to check the goodness of fit visually: >> x2=1:.1:5; >> y2=polyval(p,x2); >> plot(x,y,'o',x2,y2)

Page 8: MATLAB Tutorial Notes

7

1 1.5 2 2.5 3 3.5 4 4.5 50

50

100

150

200

250

300

350

400

450

500

Special numbrs In adition to real numbers, imaginary numbers and result of algebraic expressions that cannot be evaluated, are also defined in MATLAB. Dividing by zero is infinity (Inf) and division of zero by zero is not a number (NaN): >> x=[1 2 0]./[2 0 0] Warning: Divide by zero. x = 0.5000 Inf NaN You can use imaginary numbers as simple as real numbers in your calculations: >> y=sqrt(-1) y = 0 + 1.0000i Functions finite, isinf, isnan and isreal makes it possible to recognize these numbers: >> finite(x) ans = 1 0 0 >> isinf(x) ans = 0 1 0 >> isnan(x) ans = 0 0 1 >> isreal(x) ans =

Page 9: MATLAB Tutorial Notes

8

1 >> isreal(y) ans = 0

2D graphs The followings demonstrate how to plot a function of a single independent variable: >> x=linspace(0,2); y=x.*exp(-x); >> plot(x,y) >> grid >> xlabel('x') >> ylabel('y') >> title('y=x.e^{-x}') >> text(1,.2,'centre')

Above statements carry out the following actions:

- Creat vectors of independent variable x and function y. - Plot y against x. - Adds grid to the graph. - Adds title to the horizontal axis. - Adds title to the vertical axis. - Adds a title above the graph. - Writes a string variable (centre) at the specified point (1,0.2).

You can use different line styles when plotting functions. Also, more than one function can be plotted in a figure: >> plot(x,y,'.',x,x.*sin(x),'-.') Add a legend as follows: >> legend('x.e^{-x}','x.sin x')

Page 10: MATLAB Tutorial Notes

9

Some 2D plotting commands are listed below:

Semi-log scale plot (x-logarithmic) semilogx(x,y) Semi-log scale plot (y-logarithmic) semilogy(x,y) Log-log scale plot loglog(x,y) Polar coordinate plot polar(theta,r) Bar graph bar(x,y) Filled area plot area(x,y)

3D graphs There are various types of commends in MATLAb for visualizing 3D functions. A 3D curve can be plotted using plot3 command: >> t=0:.01:6*pi; >> plot3(cos(t),sin(t),t) >> xlabel('cos(t)') >> ylabel('sin(t)') >> zlabel('t')

Page 11: MATLAB Tutorial Notes

10

3D surfaces can be drawn by surf command: >> [x,y]=meshgrid(-pi:pi/8:pi,-pi:pi/8:pi); >> z=cos(x).*cos(y); >> surf(x,y,z) >> view(30,45)

In the above, meshgrid generates matrices of coordinates of a 2D grid that can be used for the evaluation of functions of two variables and 3D surface plots. Edges of the surface in the above graph can be smoothed by shading command. You can also see color values on the z-axis by the colorbar commans. >> shading interp >> colorbar

Page 12: MATLAB Tutorial Notes

11

m-files You can save several MATLAB commands in a file and then run them at once. Such a file should be saved with “.m” extension, thus are called m-files. If you use MATLAB editor, it saves the file with this extension by default. If you are using another text editor (such as Notepad), be sure to save the file as ascii and with .m extension. As an example, write the following program, which calculates the volume of an ideal gas at a specific pressure and temperature, in the editor and save it as pvt.m: % A sample scritp file: pvt.m disp(' Calculating the volume of an ideal gas.') R = 8314; % Gas constant (J/kmol.K) t = ... input(' Vector of temperature (K) = '); p = input(' Pressure (bar) = ')*1e5; v = R*t/p; % Ideal gas law % Plotting the results plot(t,v) xlabel('T (K)') ylabel('V (m^3/kmol)') title('Ideal gas volume vs temperature') The character % denotes comment and everything after this sign in a line will be ignored when running the program. Also, the sign “…” means that the command line is incomplete and is continued in the next line. To run this program, you can either click on the run button in the editor window or type pvt (name of the m-file) in the MATLAB window (figure is not shown below): >> pvt Calculating the volume of an ideal gas. Vector of temperature (K) = 100:25:300 Pressure (bar) = 10

Functions In addition to built-in functions in MATLAB, you can also write your own functions. A function has some input arguments and returns some other variables as outputs after required calculations. The first line is reserved for function definition and should obey the following structure: - The word function - Output arguments. These variables should be put in brakets and separated by a

comma. - The sign “=” - Name of the function. This is the name that the file should be asved with with .m

extension. - Input arguments. These variables should be put in parentheses and separated by a

comma.

Page 13: MATLAB Tutorial Notes

12

As an example, the following function, which should be saved as “ideal.m”, calculates the volume of an ideal gas as a function of pressure and temperature: function v = ideal(t,p) % ideal: Calculation of ideal gas specific volume % v=ideal(t,p) takes the vector of temperature (t) in K % and the vector of pressure (p) in Pa and returns the % matrix of specific volume (v) in m3/kmol. % Start of calculations R = 8314; % Gas constant (J/kmol.K) for k = 1:length(p) v(k,:) = R*t/p(k); % Ideal gas law end Now you can use this finction either in MATLAB command window or in a MATLAB program. For example (reults are not shown here): >> p=1:10; t=300:10:400; >> vol=ideal(t,p); >> surf(t,p,vol) >> view(135,45), colorbar It is recommended to write enough explanations, after the function declaration line, about the function (what is does, what are inouts and outputs, ect.) as comments. All continuous comment lines at the beginning of the function can be viewed by using the hep command:

>> help ideal ideal: Calculation of ideal gas specific volume v=ideal(t,p) takes the vector of temperature (t) in K and the vector of pressure (p) in Pa and returns the matrix of specific volume (v) in m3/kmol.

Control of flow of calculations MATLAB has many statements that allow the user to let the program make decisions during calculations. These statements are described below: if . . . (else . . .) end –This statement lets the program to decide which commnds should be executed. For example:

x = input(' x = '); if x >= 0 y=x^2 end

Page 14: MATLAB Tutorial Notes

13

The phrase that appears after the if statement should be a logical statement. If this logical statement is true, all commands between if and end will be executed. Otherwise, the program ignores these statemensts and continues calculations from the line after end. You can also use else in an if statement: x = input(' x = '); if x >= 0 y=x^2 else y=-x^2 end In this case, if the logical statement is true, the lines between if and else will be executed and if the logical statement is false, the lines between else and end will be executed.

for . . . end – This statement lets the program to execute a series of commands for a specific number of times. For example:

k = 0; for x = 0:0.2:1 k = k + 1 y = exp(-x) end

while . . . end – This statement is used when it is necessary to repeat a part of the program for an unknown number of times, but unti a condition is satisfied:

x = 0; while x < 1 y = sin(x) x = x + 0.1; end The phrse that follows while command is a logical statement (the condition) and lines between while and end are executed as far as this logical statement is true.

switch . . . case . . . (otherwise . . .) end – When it is required that a program execute different sequences based on different values of a variable, this statement can be used. For example:

a = input('a ='); switch a case 1

Page 15: MATLAB Tutorial Notes

14

disp('One') case 2 disp('Two') case 3 disp('Three') end pause and break: These are also useful commands in MATLAB programming. You can exit a loop (goes to the line after the corresponding “end”) when the program reaches the break command. Also, when the program reaches a pause command, it stops running and waits for the user to hit any key for continuing. See the following example: k = 0; for x = 0:0.2:1 if k > 5 disp('k > 5') break end k = k + 1; y = exp(-x); disp([' k = ',num2str(k),' y = ',num2str(y)]) pause end In the above, the program shows k and y values and waits for the user to hit any key. Then, the for loop repeats another time until k becomes equal to 5. At this pont, the command break makes the program to go to after the for loop (end of program, in this case).

Numerical Methods In this section, only a few common numerical calculatons are introduced. More advanced calculations can be carried out with MATLAB which cannot be covered in this condensed guide.

Solving set of linear algebraic equations When coefficients of a set of linear algebraic equations are consant and known, it would be very easy to solve it in MATLAB by the matrix inversion method. for example, consider the following set of equations:

132

2

0

321

321

321

xxx

xxx

xxx

This set of equations can be solved in the MATLAB command environment as follows:

>> a=[1, 1, 1; 1, -1, 1; 2, 3, -1]; >> b=[0, 2, -1]'; >> x=inv(a)*b

Page 16: MATLAB Tutorial Notes

15

x = 1 -1 0 If the coefficnts are given in formulas, it is easier to write a program for solving such set of equations. For example, consider the following set of equations whis is related to a solvent extraction tray column:

0)(

1,...,2,10)(

)(

1,...,3,20)(

)(

1

11

11

11

021

NN

iii

Ffff

iii

XmSWWX

NffimSXXmSWWX

FYXSmXSmWWX

fiXSmXSmWWX

WXXSmXSmW

In these equations, N=10, m=9, X0=0.05, F=13, S=10, S =23, YF=0.003 and f=6. The following program, named extract.m, solves this set of equations:

% extract.m clear clc % Input N=10; m=9; W=100; X0=0.05; S=10; F=13; Sbar=23; YF=0.003; f=6; % Matrix of coefficients for i = 1:f-1 if i > 1 A(i,i-1) = -W; end A(i,i) = W + m*Sbar; A(i,i+1) = -m*Sbar; end A(f,f-1) = -W; A(f,f) = W + m*Sbar; A(f,f+1) = -m*S; for i = f+1:N A(i,i-1) = -W; A(i,i) = W + m*S; if i < N A(i,i+1) = -m*S; end end % Vector of constants c = zeros(N,1); c(1) = W*X0; c(f) = F*YF;

Page 17: MATLAB Tutorial Notes

16

% Solution X = inv(A)*c

Solving a nonlinear equation In order to solve a nonlinear equation, it is required to introduce this equation in a MATLAb function. For example, for solving the following equation:

0)cos( xx You should first creat the follwing function: function y=fnc(x) y=x-cos(x); Then, use fzero to solve this equation: >> fzero('fnc',0) ans = 0.7391 In fzero, the first argument is the name of the MATLAB function which defines the equation that should be solved and the second argument is the initial guess of the root.

Interpolation MATLAB functions interp and spline carry out interpolation. Usually, spline is preferred. Consider the following example: >> x=1:5; >> y=[1 3 5 3 1]; >> xi=1:.1:5; >> yi=spline(x,y,xi); >> plot(x,y,'o',xi,yi)

Above command lines are described as follows:

Page 18: MATLAB Tutorial Notes

17

- Creats the vector of independent variable (x). - Creats the vector of function values (y), corresponding to x. - Vector of independent vriable at which the function should be evaluated by

interpolation is introduced (xi). - Function values corresponding to xi values (yi) are evaluated by interpolation. - Base points are plotted as circles and interpolated values are plotted with

continuous curve.

Intgration There are two ways to evaluate a definite integral in MATLAB. If the independent variable and the function are available as vectors, you can calculate the integral by trapz whis evaluates the integral by the trapezoidal rule:

>> x=[2:10]; >> y=[0.3466, 0.3662, 0.3466, 0.3219, 0.2986, 0.2780, 0.2599, 0.2441, 0.2303]; >> trapz(x,y) ans = 2.4038 In this example, vectors of independent and function values are introduced in first and second lines, respectively and the third line evaluates the integral. Obviously, this method is applied to cases where the relationship between dependent and independent variables are not given as a function, but they are available as two vectors. If the algebraic function that relates dependent and independent variables is known, you can use the command quad for evaluating the definit integral. For this purpose, you need to define this function in a MATLAB function, first. For example, for evaluating the following integral:

10

2

lndx

x

xy

You should first creat the following MATLAB function: function y=intln(x) y=log(x)./x; Then, use quad to evaluate the integral value:

>> quad('intln',2,10) ans = 2.4107 Input areguments to quad are name of the integrand function, lower limit and upper limit of integral, respectively.

Solving ordinary differential equations There are many MATLAB functions that can solve ordinary differential equations (initial value problem) among which ode45 is the most common one. Before solving a

Page 19: MATLAB Tutorial Notes

18

first order ordinary differential equation in MATLAB, first you need to creat a function which contains the derivative. For example, for solving the following equation:

0)0(2 yyxdx

dy

You should first creat the following MATLAB function:

function dy=fode(x,y) dy=x^2+y; Then, use ode45 to sove it: >> [x,y]=ode45('fode',[0,1],0); >> plot(x,y)

In ode45, the first input argument is the name of the file, the second one is a vector in which its first and last elemnt are lower and upper limit of independent variable, respectively, and the third argument is the function value at initial condition. If the order of the differential equation is greater than one, it should be first converted to a set of first order differential equations and then solve them simultaneously. For example, consider the following equation:

02 ybyay This equation can be presented in its canonical from as follows:

Page 20: MATLAB Tutorial Notes

19

12

22

21

ybaydx

dy

ydx

dy

In these equations y1=y and y2=y’. This set of differential equations is presented in the following function: function [Ydot] = myode(x,Y) % Note: Y(1) =Y1 and Y(2) =Y2 % x is independent variable. If your equations do not % contain x, you still have to put a "x" in the function % declaration above. A = 1.3333; % Whatever values you want to choose B= 2.132; Ydot(1) = Y(2); Ydot(2) = -A*Y(2)-B^2*Y(1); Ydot=Ydot'; Now, we solve this with ode45: >> [x,y]=ode45('myode',[0,10],[0,1]); >> plot(x,y)