You are on page 1of 37

SECTION A

INTRODUCTION & BASICS


MATLAB, (Stands for MATrix LABoratory) developed by The MathWorks, Inc., integrates computation, visualization, and programming in a flexible, open environment. It offers engineers, scientists, and mathematicians an intuitive language for expressing problems and their solutions mathematically and graphically. Complex numeric and symbolic problems can be solved in a fraction of the time required with a programming language such as C, FORTRAN, or Java. MATLAB allows the user to input data in the format of a matrix and use matrix calculations to solve the different problems. Therefore a sound knowledge in the matrix calculation is needed to achieve the full use of MATLAB. Starting MATLAB In Microsoft Windows, MATLAB can be started directly by clicking the MATLAB Icon.

Or else you can find MATLAB in the program menu. For example; START >> ALL PROGRAMS >> MATLAB >> MATLAB R2007b

Start Button The Start button in the bottom left corner of the MATLAB Desktop allows you to start up demos, tools, and other windows not present when you start MATLAB.Try Start: MATLAB: Demos and run one of the demos from the MATLAB Demo window.
1|Page

Command Window MATLAB expressions and statements are evaluated as you type them in the Command window, and results of the computation are displayed there too. Expressions and statements are also used in Mfiles. They are usually of the form: Variable = expression Or simply: Expression

Workspace Window The Workspace window lists variables that you have either entered or computed in your MATLAB session. Command History Window This window lists the commands typed in so far. You can re-execute a command from this window by double-clicking or dragging the command into the Command window. Current Directory Window Your current directory is where MATLAB looks for your M-files, and for workspace (.mat) files that you load and save. You can also load and save matrices as ASCII files and edit them with your favorite text editor.

2|Page

SIMPLE CALCULATIONS USING MATLAB


MATLAB uses simple arithmetic operators + - / * ^ to indicate addition, subtraction, division, multiplication and raised-to-the power respectively. First lets try some simple examples. 1. 5+4 =? Try entering 5+4 in the command window. You will get the answer in the following format. >> 5+4 ans = 9 Note: MATLAB automatically creates a variable called ans in the workspace and refreshes it after each calculation. 2. 2+3^4=? >> 2+3^4 ans = 83 3. Multiply the above answer by 2. >> ans*2 ans = 166 4. Try

Then lets try defining variables and use them in our calculations.

Try to find F, if m = 10 and a = 2. First you have to define your known variables, m and a. This can be done as follows.

3|Page

>> m = 10 m= 10 The echo of our input can be removed by introducing a semi-colon (;) just after the expression. For example lets define a in that way. >> a = 2; >> Now you can see that there is no echo in the command window. But introducing the semi-colon just after a calculation will prevent MATLAB from showing the result. Now we can calculate F. >> F = m * a F= 20 We can repeat the same with a semi-colon. >> F = m * a; >> Now it will not show the result. To see the value of F and other defined variables, you can enter the name of the variable. (Note: Remember that MATLAB is case sensitive). >> a a= 2 >> m m= 10 >> F F= 20

Other mathematical functions used in MATLAB


4|Page

abs acos, acosh acot, acoth acsc, acsch angle asec, asech asin, asinh atan, atanh atan2 bessel ceil conj cos, cosh cot, coth csc, csch erf exp fix floor gamma imag log log2 log10 mod rat

Absolute value Inverse cosine, inverse hyperbolic cosine Inverse cotangent, inverse hyperbolic cotangent Inverse cosecant, and inverse hyperbolic cosecant Phase angle Inverse secant, inverse hyperbolic secant Inverse sine, inverse hyperbolic sine Inverse tangent (two quadrant), inverse hyperbolic tangent Inverse tangent (four quadrant) Bessel function Round up Complex conjugate Cosine, hyperbolic cosine Cotangent, hyperbolic cotangent Cosecant, hyperbolic cosecant Error function Exponential Round toward zero Round down Gamma function Imaginary part Natural logarithm Dissect floating-point numbers into exponent and mantissa Common logarithm Modulus (signed remainder after division) Rational approximation

5|Page

SECTION B
VECTOR & MATRIX CALCULATIONS USING MATLAB
In MATLAB, there are two types of vectors: the row vectors and column vectors. ROW VECTORS The row vectors are entities enclosed in pair of square-brackets with numbers separated either by spaces or by commas. For example, you may enter two vectors U and V as: >> U = [1 2 3]

U=

You can define V separated by commas as follows, >> V = [4, 5, 6]

V=

Now lets perform some simple mathematical operations on these two row vectors. 1. Addition To add two row vectors, they must be identical in size. Try to add U & V. >> W = U + V W= 5 7 9

2. Subtraction >> X = V - U X= 3 3 3
6|Page

Or, >> Y = U - V Y= -3 -3 -3

3. Multiplication of a row vector by a scalar A row vector can be multiplied by a scalar which will result of multiplication of each and every element by the value of the scalar. For example, lets calculate 5 * U by using MATLAB. >> 5 * U ans = 5 10 15

Now find the value of the following expression. 2*U+3*V 4. Scalar multiplication of two row vectors. Two row vectors identical in size can be multiplied through scalar multiplication. The answer also will be in the format of a row vector. U = [u1 u2 u3] and V = [v1 v2 v3] U.V = [(u1* v1) ( u2*v2) (u3*v3)] In MATLAB, this will be denoted as U.*V. >> U.*V ans = 4 10 18

5. Combination of two row vectors to form another vector.

>> W = [U, V]

7|Page

W= 1 2 3 4 5 6

The vector U and V both of length 3, have been combined to form a six component vector W. 6. Sorting of elements inside a row vector. You can sort the elements of a vector can be sorted with the help of the sort function. >> Z = [4 9 5 8 23 15 2 4 96 53 62 35 22 33 78] Z= 4 9 5 8 23 15 2 4 96 53 62 35 22 33 78

Now lets try to sort the elements of this vector. >> sort (Z) ans = 2 4 4 5 8 9 15 22 23 33 35 53 62 78 96

This can be very useful when you are handling a set of statistical or experimental data in MATLAB.

THE COLON NOTATION In order to form a vector as a sequence of numbers, one may use the colon notation. According to which, a: b: c yields a sequence of numbers starting with a, and possibly ending with c in steps of b. For example 1:0.5:2 yields following column vector: >> a = 1:0.5:2

a=

1.0000

1.5000

2.0000

Note that in some cases, the upper limit may not be attainable thing. For example, in case of 1:0.3:2, the upper limit is not reached and the resulting vector in this case is: >> b = 1:0.3:2
8|Page

b= 1.0000 1.3000 1.6000 1.9000

If only two of the range specifications are given then a unit step size is automatically assumed. For example 1:4 means: >> 1:4

ans =

In case, the range is not valid, an error message is issued: >> 1:-1:5

ans =

Empty matrix: 1-by-0

You can also define a row vector by using the combinations of the colon notations. For example: >> T = [2:2:16, 3:3:24]

T=

10

12

14

16

12

15

18

21

24

Or, >> S = [1:5, 3:7, 5:9]

S=
9|Page

COLUMN VECTORS The column vectors in MATLAB are formed by using a set of numbers in a pair of square brackets and separating them with semi-colon. Therefore, one can define two column vectors A and B and add them as below: >> A = [1; 2; 3], B= [4; 5; 6] A= 1 2 3 B= 4 5 6 The addition of the above two column vectors will give, >> A+B ans = 5 7 9 The other method to define a column vector is to define a row vector first and get the transpose of it. For example, define a row vector C = [1 2 3] and get the transpose of it. >> C = [1 2 3] C= 1 2 3

>> D = C' D=
10 | P a g e

1 2 3

MATRICES A matrix is essentially a two dimensional array of numbers composed of rows and columns. A matrix can be entered in MATLAB in any of the following five ways: a) Using the RETURN key Lets define a 3 X 3 Matrix as follows. >> A = [1 2 3 456 7 8 9] A= 1 2 3 4 5 6 7 8 9 b) Using semicolons to indicate the next line >> A = [1 2 3; 4 5 6; 7 8 9] A= 1 2 3 4 5 6 7 8 9 c) Using the range notation with semicolon >> A = [1:3; 4:6; 7:9] A= 1 2 3 4 5 6 7 8 9 d) By combination of set of predefined row vectors First define the each row of the matrix as separate row vectors as follows. >> A1 = [1 2 3] A1 =
11 | P a g e

>> A2 = [4 5 6] A2 = 4 5 6

>> A3 = [7 8 9] A3 = 7 8 9

Then combine the above three vectors to form the matrix A. >> A = [A1; A2; A3] A= 1 4 7 2 5 8 3 6 9

e) First define the each column of the matrix as separate column vectors as follows. >> A1 = [1 4 7]' A1 = 1 4 7 >> A2 = [2 5 8]' A2 = 2 5 8 >> A3 = [3 6 9]' A3 =
12 | P a g e

3 6 9

Then combine the above three column vectors to form matrix A. >> A = [A1 A2 A3] A= 1 4 7 2 5 8 3 6 9

Defining special matrices

Zero matrix A zero matrix can be defined by using the following function. Zeros(m,n) or simply zeros(m) if m=n. For example, >> zeros(3) ans = 0 0 0 0 0 0 0 0 0

>> zeros(2,4) ans = 0 0 0 0 0 0 0 0

Unit matrix >> ones(3) ans =


13 | P a g e

1 1 1

1 1 1

1 1 1

>> ones(2,4) ans = 1 1 1 1 1 1 1 1

Identity matrix This is the special matrix in which all the diagonal elements are 1 and all other elements are 0. Therefore by the definition itself, the matrix must be a square matrix. >> eye(3) ans = 1 0 0 0 1 0 0 0 1

Random matrix This will be a random matrix in which all the elements are defined randomly in between 0 to 1. >> rand(3) ans = 0.8147 0.9058 0.1270 0.9134 0.6324 0.0975 0.2785 0.5469 0.9575

>> rand(2,4) ans = 0.9649 0.1576 0.9706 0.9572 0.4854 0.8003 0.1419 0.4218

Matrix calculations
14 | P a g e

Transpose of a matrix The transpose of a matrix A(m,n) will result in a new matrix B(n,m). >> A = [1 2 3; 4 5 6; 7 8 9] A= 1 4 7 2 5 8 3 6 9

>> transpose(A) ans = 1 2 3 4 5 6 7 8 9

>> B = [1 2; 4 5; 7 8] B= 1 4 7 2 5 8

>> transpose(B) ans = 1 2 4 5 7 8

Matrix addition/subtraction To add/subtract two matrices, they must be identical in dimensions. >> A = [1 2 3; 4 5 6; 7 8 9] A= 1 4 7 2 5 8 3 6 9
15 | P a g e

>> B = [9 8 7; 6 5 4; 3 2 1] B= 9 6 3 8 5 2 7 4 1

>> A+B ans = 10 10 10 >> A-B ans = -8 -2 4 -6 0 6 -4 2 8 10 10 10 10 10 10

Matrix multiplication To multiply two matrices, their dimensions must be in the following format. C(m,p) = A(m,n) X B(n,p) i.e.: The number of columns of the first matrix must be equal to the number of rows in the second matrix. If this condition is not met, MATLAB will generate an error message. Example 1; >> A = [1 2 3; 4 5 6; 7 8 9] A= 1 4 7 2 5 8 3 6 9

>> B = [9 8 7; 6 5 4; 3 2 1]

16 | P a g e

B= 9 6 3 >> A*B ans = 30 24 18 84 69 54 138 114 90 Example 2: >> A = [1 2; 4 5; 7 8; 1 2] A= 1 4 7 1 2 5 8 2 8 5 2 7 4 1

>> B = [1 2 3; 4 5 6] B= 1 4 >> A*B ans = 9 12 15 24 33 42 39 54 69 9 12 15 Tip: you can retrieve the size of ay matrix by using the function size () >> size (A) ans =
17 | P a g e

2 5

3 6

>> size (B) ans = 2 3

>> size (A*B) ans = 4 3

Now Try B*A. >> B*A ??? Error using ==> mtimes Inner matrix dimensions must agree. It will give you a message that the inner dimensions of the matrix are wrong. Inverse of a matrix You can find the inverse of a square matrix provided that it is non-singular. (Det(Matrix) is not equal to zero) For a non-singular matrix, MATLAB will give, >> A = [1 2 3; 4 8 9; 1 2 3] A= 1 4 1 2 8 2 3 9 3

>> inv(A) Warning: Matrix is singular to working precision. ans = Inf Inf Inf Inf Inf Inf Inf Inf Inf
18 | P a g e

For a singular matrix, >> A = [4 6 3; 8 5 2; 7 6 1] A= 4 8 7 6 5 6 3 2 1

>> inv(A) ans = -0.1489 0.2553 -0.0638 0.1277 -0.3617 0.3404 0.2766 0.3830 -0.5957 What is the answer of A* inv (A)??? >> A*inv (A) ans = 1.0000 -0.0000 0 -0.0000 1.0000 0.0000 -0.0000 -0.0000 1.0000 It is the identity matrix, I. The determinant of matrix The determinant of a matrix can be found by using the det () function.

>> A = [1 5 9 853 9 4 3] A= 1 8 9 5 5 4 9 3 3

19 | P a g e

>> det (A) ans = -99

20 | P a g e

SECTION C
PLOTTING GRAPHS & CURVE FITTING
MATLAB offers powerful tools and functions to plot graphs and for other visualization methods. The Curve Fitting Toolbox (cftool) provides a collection of tools that can be used for potting data, and selecting the type of graph, and editing the plot and especially regression analysis of a given dataset. In addition to that the function, plot() can be used plotting a set of data that are stored in vectors. First we will use the plot function to plot the graph of sin(x) in the range of 0 to 2. Example 1: Plot the graph of sin(x) in 0<x<2 Method: Before thinking about plotting the graph, we have to find the value of the function sin(x) at certain x values in the given range. Therefore first we will define discrete intervals at which points the function will be calculated. For that first we will define a new variable called N which stands for the number of intervals. >> N = 40 N= 40 Then we will define the interval that we need as follows. >> h = 2 * pi / 40; Then we will use the colon notation to create a row vector which includes the points at which we will calculate the value of the function. >> x = 0: h: 2*pi You will see a row vector called x has been created with 41 elements (which is 40+1). Now we will evaluate the function at those elements. >> y = sin(x); >> y y= Columns 1 through 9 0 0.1564 0.3090 0.4540 0.5878 0.7071 0.8090 0.8910 0.9511

Columns 10 through 18
21 | P a g e

0.9877

1.0000

0.9877

0.9511

0.8910

0.8090

0.7071

0.5878

0.4540

Columns 19 through 27 0.3090 0.1564 0.0000 -0.1564 -0.3090 -0.4540 -0.5878 -0.7071 -0.8090

Columns 28 through 36 -0.8910 -0.9511 -0.9877 -1.0000 -0.9877 -0.9511 -0.8910 -0.8090 -0.7071 Columns 37 through 41 -0.5878 -0.4540 -0.3090 -0.1564 -0.0000

Now having calculated the function, the function can be plotted simply by using the plot command in the following format. plot(x data, y data) >> plot(x,y) You can see the graph in a separate window called Figure 1.

22 | P a g e

The above graph is not complete unless we clearly label it. Therefore we will learn how to label a graph and its various components. You can edit the same plot (figure) in the command window after entering the command hold on. You can release the plot eventually the command hold off. First we will type the title of the graph. You can type the following command for this purpose. >> hold on >> title('Sin X') You will see the title Sin X in the top of the graph. Similarly the commands xlabel and ylabel will insert the labels for the x-axis and y-axis respectively. Finally the graph will look like as follows.

Now release the plot by typing the command hold off.

Multiple Plots on the Same Axis In certain situations, we find multiple plots (graphs) on the same axis. In such situations, they must be drawn in a way, so that they are easily differentiated from each other. For that purpose, we can
23 | P a g e

change the line color, line pattern and point symbols by using specific parameters inside the plot function. Example: Plot sin x and cos x (0<x<2) in the same axis. As in the previous example, first define the range and calculate sin x and cos x as two separate row vectors. >> N = 40; >> h = 2 * pi / N; >> x = 0:h:2*pi; >> y1 = sin(x); >> y2 = cos(x); It is possible to plot these two functions in the same axis by using the plot() function in the following manner.

MATLAB will automatically use two colors for the plot, but we cant identify the plots clearly. Therefore we will try to modify the parameters inside the plot function to format the plot. >> plot(x,y1,x,y2)
24 | P a g e

>> hold on >> title('Sin X & Cos X') >> xlabel('X') >> legend('Sin X', 'Cos X') Now the plot will look like as follows.

If you want to change the color and pattern of a plot, you can modify the plot command as follows. >> plot(x,y1,'bx-',x,y2,'c+-') This will plot the Sin X function in blue color with x-mark pointers connected with solid line and Cos X function in cyan color with +-mark pointers connected with dashed line. The following are the options that you can use to format the plot as above. Color b g r blue green red Pointer . o x point circle x-mark : -. Line Type solid dotted dashdot
25 | P a g e

c m y k w

cyan magenta yellow black white

+ * s d v ^ < > p h

plus star square diamond triangle (down) triangle (up) triangle (left) triangle (right) pentagram hexagram

-- dashed (none) no line

Subplots Sometimes we need to plot two or three graphs adjacent to each other but not on the same axis. The command subplot can be used to plot graphs in a matrix of graphs. For example, subplot(3,1,1) will
26 | P a g e

first create a 3 X 1 panel (with 3 rows and 1 column) and draw the graph in the first space. Likewise subplot(3,1,3) will draw the graph in the third space. Example: Draw Sin X and cos X in a 1X2 panel of plots. >> N = 40; >> h = 2 * pi / 40; >> x = 0:h:2*pi; >> subplot(1,2,1) >> plot(x,sin(x),'bx-'); >> xlabel('X') >> ylabel('Sin X') >> title('Sin X') >> subplot(1,2,2) >> plot(x,cos(x),'r+-') >> xlabel('X') >> ylabel('Cos X') >> title('Cos X') This will give you the following figure.

27 | P a g e

Curve Fitting Tool (cftool) The curve fitting tool is a very effective mathematical and statistical tool in MATLAB. As the name implies, it can be used for curve fitting or in other words for regression analysis. For example suppose, you have following experimental data. X1 Y1 5 12 10 23 15 38 20 47 25 62 30 77 35 87 40 95 45 110 50 123

Suppose, in theory that these data can be related as follows.

So by using the experimental data, you are required to find the values of m and c. For that, you need to find the linear regression curve for the above dataset. MALAB can be used to find it easily. First define the two varibales X1 and Y1 as two row vectors. >> X1 = 5:5:50; >> Y1 = [12 23 38 47 62 77 87 95 110 123];

Then type the command cftool in the command window. The following window should appear.

28 | P a g e

Click the data button to enter X1 and Y1 data.

You can select appropriate X data and y data by using the drop down boxes.

29 | P a g e

After selecting data, then click Create data set button. Then close the dialog box. You will see the main dialog box as follows.

Now click the Fitting button and it will display the following window in which the fitting parameters can be adjusted.

30 | P a g e

In this dialog box, click New fit button.

31 | P a g e

In that window you can select the appropriate type of fitting. For this example, select linear polynomial. Then click apply. You will get the results for m and c, as p1 and p2.

32 | P a g e

So the equation would be as follows.

Now if you turn to the main Curve fitting tool window, you will see the following.

33 | P a g e

You can change the options in the curve fitting tool and achieve the desired fitting requirements.

34 | P a g e

EXERCISES:
SECTION A: 1. 3*2^4 2. (3*2)^4 3. 3-2^4 4. 3^4-3 5. 8/2^4 6. 2^4\8 7. 8^4/2 SECTION B 1. x = [3 4 7 11] 2. x = 3:8 3. x = 8:-1:0 % create a row vector (spaces) % colon generates list; default stride 1 % hstarti : hstridei : hstopi specifies list % same as last; semicolon suppresses output % display contents % generate vector automatically % same thing % note semicolon! % same as previous! two different divisions, \ and / % parentheses have highest priority

4. xx = [ 8 7 6 5 4 3 2 1 0]; 5. xx 6. x = linspace(0,1,11) 7. x = 0:0.1:1 8. y = linspace(0,1); 9. length(x) 10. length(y) 11. size(x) 12. size(y) 13. y(3) 14. y(1:12) 15. y([3 6 9 12]) 16. x' % transpose 17. z = [ 1+2*i 4-3*i ] 18. g = [1; 2; 3; 4] 19. g = [1 2 3 4; 5 6 7 8] 20. g - 2 21. 2*g-1

% access single element % access first twelve elements % access values specified in a vector!

22. g = [1 2 3 4; 5 6 7 8; 9 10 11 12] 23. h = [1 1 1 1; 2 2 2 2; 3 3 3 3] 24. g-h


35 | P a g e

25. g*h 26. h*g 27. g.*h 28. g./h 29. h.\g 30. g*h' 31. g'*h 32. e = [ 1 2 3; 4 5 6; 7 8 0] 33. f = [9 8 7; 6 5 4; 3 2 1] 34. e*f 35. f*e 36. q = rand(3) 37. A^2 38. A^2 - A*A 39. A.^2 40. A.^2 - A*A 41. ones(3) 42. zeros(2,5) 43. size(zeros(2,5)) 44. size(g) 45. ones(size(g)) 46. eye(4) 47. eye(2,4) 48. eye(4,2) 49. rand(3) 50. b = eye(3) 51. rand(size(b)) 52. a = 1:4 53. diag(a) 54. diag(a,1) 55. diag(a,-2) 56. A = rand(5) 57. b = rand(5,1) 58. det(A) 59. inv(A) 60. B = rand(5) 61. A*B

% What happened?

% NOT the usual matrix multiplication! Elementwise! % elementwise division; denominator below slash % Last two same!

% Not same! % matrix with elements uniformly on [0,1] % raise matrix to a power % verify with definition % square each element % not the same! % All ones % All zeros

% Identity matrix

% Random elements uniformly distributed between 0 and 1

% matrix of coefficients from Ax=b % right hand side % determinant of A % inverse of A

36 | P a g e

62. B*A

% Are they same?

SECTION C 1. Plot ex in the range of 0<x<10 with appropriate title and axis labels. 2. Plot ex-1 and ex-1 with in the same region with appropriate title, axis labels and legends and with different formatting. 3. Plot tan x, sin x and cos x in 3X1 subplot. 4. Find m and c, so that the equation is y = mx+c x y 2 23 4 45 6 75 8 98 10 110 12 148 14 170 16 199 18 213 20 248

5. Find m, so that the equation is y = mx x y 0.5 3.4 1 6.5 1.5 9.5 2 13.3 2.5 17.4 3 19.1 3.5 22.7 4 26.9 4.5 28.1 5 34.2

37 | P a g e

You might also like