You are on page 1of 107

CHAPTER:-1

STARTING WITH MATLAB

1.1 Start MATLAB:-


Logging into your account. You can enter MATLAB by double clicking on the
MATLAB shortcut icon on your window desktop. When you start MATLAB, a
special window called the MATLAB desktop appears. The major tools within from
the desktop are:-

Command window
Command history
Workspace
Current directory
Help browser
Start button

1.2 What is MATLAB:-


MATLAB stands for matrix laboratory. MATLAB is a software package which can
be used to perform analysis and solve mathematic and engineering problem.

MATLAB is a very popular language for technical computing used by students,


engineers, scientists in universities, research institutes, and industries all over the
world.

MATLAB is initially developed by a lecturer in 1970s to help students learn linear


algebra.

MATLAB was written originally to provide easy access to matrix software developed
by the LINPACK (linear system package) and EISPACK (Eigen system package)
projects.

MATLAB handles simple numerical expressions and mathematical formulas.

MATLAB is a high performance language for technical computing. It integrates


computation, visualization, and programming environment.

MATLAB has many advantages compared to conventional computer languages (e.g.,


C, FORTRAN) for solving technical problems.

1
1.3 Using MATLAB as a calculator:-

For example, lets suppose you want to calculate the expression in command
window, 4+6*9. You type it at the prompt () as follows,

>> 4+6*9

ans =

58

You will have noticed that if you do not specify an output variable, MATLAB uses a
default variable answer, to store the result for current calculation. You may assign a
value to a variable or argument name.

For example, x = 4+6*9.

>> 4+6*9

ans =

58

>> which is called a prompt command.

1.4 Basic arithmetic operators:-

SYMBOL OPERATOR EXAMPLE


+ Addition 9+3

- Subtraction 4-5

* Multiplication 2*10

/ Division 2/11

Using arithmetic operator in command window:

a) Addition, for example, x = 56+50


>> x=56+50

x=

106

b) Subtraction:-
For example, y=45- 34

2
>> y=45- 34

y=

11

c) Multiplication:-
For example, z= 4*7

>> z=4*7

z=

28

d) Division:-
For example, v= 56/29

>> v= 56/29

v=

1.9310

Lets consider the arithmetic operation, but we will include parentheses.

For example, 8+7*9 will become (8+7)*9

>> (8+7)*9

ans =

135

Now, parentheses are missing, 8+7*9

>> 8+7*9

ans =

71

By adding parentheses, these two expression give different results: 135 and 71.

1.5 Controlling the hierarchy of operation or precedence:-


MATLAB arithmetic operators obey the same precedence rules as those in most
computer programs. For operators of equal precedence, evolution is form left to right.

Now consider example:

3
1/4+ +6/7*3/5

In MATLAB, it becomes

>> 1/ (4+3^2) +6/7*3/5

ans =

0.5912

If parentheses are missing,

>> 1/4+3^2+6/7*3/5

ans =

9.7643

1.6 Creating MATLAB variables:-


MATLAB variable is created with an assignment statement. The syntax of variable
assignment is

Variable name = a value (or a expression)

For example, x= expression

Where expression is a combination of numerical values, mathematical operators,


variables, and function calls.

Then x= 9+7*8-5,

>> x= 9+7*8-5

x=

60

1.7 Overwriting variable:-


Once a variable has been created, it can be reassigned. In addition, if you do not wish
to see the intermediate results, you can suppress the numerical output by putting a
semicolon (;) at the end of the line. Then the sequence of commands is, For example,

>> w=9;

>> w=w+55

w=

64

4
1.8 Controlling the appearance of floating point number:-
MATLAB by default displays only 4 decimals in the result of the calculations, for
example, -234.5675. However, MATLAB does numerical calculations in double
precision, which is 15 digits. The command format controls how the results of
computations are displayed. Here are some examples of the dierent formats together
with the resulting outputs.

>> format short

>> x=-234.5675

x=

-234.5675

>> format long

>> x=-234.5675

If we want to see all 15 digits, we use the command format long.

x=

-2.345675000000000e+02

1.9 Entering multiple statements per line:-


It is possible to enter multiple statements per line. Use commas (,) or semicolons (;) to
enter more than one statement at once. Commas (,) allow multiple statements per line
without suppressing output.

For example,

>> x=8; y= tan(x), z= sinh(x)

y=

-6.7997

z=

1.4905e+03

5
CHAPTER:-2
CREATING ARRAYS AND BASIC PLOTTING

2.1 Mathematical functions:-


MATLAB offers many predefined mathematical functions for technical computing
which contains a large set of mathematical functions. There is a long list of
mathematical functions that are built into MATLAB. Lists some commonly used
functions, where variable x and y can be numbers, vector, or matrices.

Table 2.1.1 Elementary functions:


Cos(x) Cosine Abs(x) Absolute value
Sin(x) Sine Sign(x) Signum function
Tan(x) Tangent Max(x) Maximum value
acos(x) Arc cosine Min(x) Minimum value
asine(x) Arc sine Ceil(x) Round towards +
atan(x) Arc tangent Floor(x) Round toward -
Exp(x) Exponential Round(x) Round to nearest integer
Sqrt(x) Square root Rem(x) Remainder after divison
Log(x) Natural logarithm Angle(x) Phase angle
Log10(x) Common logarithm Conj(x) Complex conjugate

Table 2.1.2 Predefine constant values:

Pi The number, =3.14159..


i, j The imaginary unit i, -1
Inf The infinity,
NaN Not a number

Example:
1) The value of expression y = sin(y) +15x, for a = 12, x= 5, and y = 9 is
computed by

>> a=12; x=5; y=9;

>> z=exp(-a)*sin(y) +15*sqrt(x)

z=

33.5410

6
The subsequent examples are

>> v=log (65)

v=

4.1744

>> v=log10 (65)

v=

1.8129

2) To calculate the value of cos(i), , x= 1/0, y =sin( ), cos( )and we


enter the following command in MATLAB.

>> i=sqrt(-1)

i=

0 + 1.0000i

>> cos(i)

ans =

1.5431

>> exp(inf)

ans =

Inf

>> x=1/0

x=

Inf

>> y=sin(inf)

y=

NaN

>> cos(pi/4)

ans =

0.7071

7
>> exp(10)

ans =

2.2026e+04

2.2 Basic plotting:-

2.2.1 Creating simple plot:-


The MATLAB command to plot a graph is plot(x, y).The vectors x= (1, 4, 5, 6, 9, 12)
and y= (4, -2, 4, 8, 7, 11)

>> x= [1 4 5 6 9 12];

>> y= [4 -2 4 8 7 11];

>> plot(x,y)

>> title('simple function')

>> xlabel('x--->')

>> ylabel('y--->')

8
2.2.2 Creating a Sine wave (one dimensional plot):-
To create a Sine wave in MATLAB command window.

>> x=0: pi/100:2*pi;

>> y=sin(x);

>> plot(x,y,'g-')

>> title('sine wave')

>> xlabel('x-axis')

>> ylabel('y-axis')

Similarly create a cos and tan wave in matlab command window.

>> plot(x,y)

>> x= linspace(0,2*pi,100);

>> y= cos(x);

>> plot(x,y,'r--' )

9
2.2.3 Create a two dimensional plot:-
>> x=linspace(0,2*pi,100);

>> y=sin(x);

>> z=cos(x);

>> plot(x,y,'r-')

>> hold

Current plot held

>> plot(x,z,'g--')

10
2.2.4 Create a three dimensional plot:-

1)
>> x=linspace(0,(2*pi),100);

>> y=sin(x);

>> z=cos(x);

>> w=tan(x);

>> plot(x,y,'r-',x,z,'g--',x,w,'b:')

11
2)
>> x=0:pi/100:2*pi;

>> y1=3*sin(x);

>> y2=2*tan(x);

>> y3=cos(x);

>> plot(x,y1,'-',x,y2,':',x,y3,'--')

>> xlabel('0\leq x\leq 2\pi')

>> legend('3*sin(x)','2*tan(x)','cos(x)')

12
2.2.5 Multiple data sets in one plot:-
For example, these statement plot three related function of

x: y1=2cos(x), y2=cos(x), and y3=0.5*cos(x), in the interval 0 x 2 .

>> x=0: pi/100:2*pi;

>> y1=2*cos(x);

>> y2=cos(x);

>> y3=0.5*cos(x);

>> plot(x,y1,'--',x,y2,'-',x,y3,':')

>> xlabel('0 \leq x \leq 2\pi')

>> ylabel('cosine function')

>> legend('2*cos(x)','cos(x)','0.5*cos(x)')

>> title('example of multiple plots')

>> axis([0 2*pi -3 3])

13
2.3 Matrix generation:-
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with
matrix generation and manipulation. Matrices can be generated in several ways.

2.3.1 Entering a vector (One-dimensional array):-


A one dimensional array is a list of numbers arranged in row or a column.A vector is
a special case of matrix. An array of dimension 1x n is called a row vector, whereas
an array of dimension m x 1 is called column vector. The element of row vector are
separated by spaces and element of column vector are separated by semicolon (;).

For example, to enter a row vector u,

>> u=[ 3 4 7 8 9]

u=

3 4 7 8 9

To enter a column vector, v,

14
>> v= [2; 6;9;8;5]

v=

Now to access the first three element of u, we have,

>> u(1:3)

ans =

3 4 7

To find a particular value of u form first row and forth column in MATLAB.

>> u(1,5)

ans =

Produces a column vector, we have,

>> u(:)

ans =

Produces a row vector, of u we have,

>> u(1:end)

ans =

3 4 7 8 9

15
2.3.2 Entering a matrix (Two dimensional array):-
Two dimensional array, is also called a matrix, has numbers in rows and columns.

A matrix is an array of numbers. To type matrix into MATLAB,

For example,

A matrix in MATLAB begin with a square bracket,[

Separated element in a row with spaces and use a semicolon (;) to separate rows then
end the matrix with another square bracket,].

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

B=

6 5 6

4 9 1

1 1 3

To find a particular element of a matrix B by specifying its location. We have,

>> B(3,1)

ans =

2.3.3 Matrix indexing:-


In a matrix B (2.3.2) we select element in matrix, the element of the row i and
column j of the matrix B is denoted by B(i, j). The index is the row number and the
second index is the column number.

In matrix B for example, B (2, 3) is an element of second row and third column.
Here B (2, 3) = 1. Now, correcting any entry is easy through indexing. Here we
substitute B(3,2)=1 by B(3,2)=8 then

>> B(3,2)=8

B=

6 5 6

4 9 1

1 8 3

16
2.3.4 Transposing a matrix:-
A matrix is given by,

>> A=[1 5 3;2 2 6;7 9 5]

A=

1 5 3

2 2 6

7 9 5

>> A'

ans =

1 2 7

5 2 9

3 6 5

2.3.5 Creating a sub-matrix:-


A matrix a is given by,

>> A=[4 5 6;3 2 1;6 8 5]

A=

4 5 6

3 2 1

6 8 5

A Sub matrix B consisting of rows 1 and 3 and column 2 and 3 of the matrix A,
then

>> B=A([1 3],[2 3])

B=

17
5 6

8 5

Now to interchange rows 1 and 3 of matrix A we have,

>> C=A([3 2 1],:)

C=

6 8 5

3 2 1

4 5 6

To find a particular value of matrix A using A(end:-1:1,end),

>> A(end:-1:1,end)

ans =

2.3.6 Colon operator:-


Colon operator is very important operator in MATLAB. That means to.

It is denoted by (:).

For example,

To find the value 1 to 10 in MATLAB command window.

>> 1:10

ans =

1 2 3 4 5 6 7 8 9 10

And find the value 1 to 20 with space 2 using in command window.

>> 1:2:20

ans =

1 3 5 7 9 11 13 15 17 19

18
2.3.7 Linear Spacing:-
There is a command to generate linear spaced vectors: linspace. It is similar to the
colon operator (:),

For example,

Y= linspace(a, b)

Creating a vector with linear spacing by specifying the first and last terms, and the
number of terms:-

For example,

1) we want to construct vector of say 10 elements between 0 and 15.

>> x= linspace(0,15,10)

x=

Columns 1 through 7

0 1.6667 3.3333 5.0000 6.6667 8.3333 10.0000

Columns 8 through 10

11.6667 13.3333 15.0000

2) Now we construct vector of say 40 elements between 0 and 2.

>> y=linspace(0,2*pi,40)

y=

Columns 1 through 3

0 0.161107315568707 0.322214631137415

Columns 4 through 6

0.483321946706122 0.644429262274829 0.805536577843537

Columns 7 through 9

0.966643893412244 1.127751208980951 1.288858524549659

Columns 10 through 12

1.449965840118366 1.611073155687073 1.772180471255781

Columns 13 through 15

19
1.933287786824488 2.094395102393196 2.255502417961903

Columns 16 through 18

2.416609733530610 2.577717049099317 2.738824364668025

Columns 19 through 21

2.899931680236732 3.061038995805439 3.222146311374147

Columns 22 through 24

3.383253626942854 3.544360942511561 3.705468258080269

Columns 25 through 27

3.866575573648976 4.027682889217684 4.188790204786391

Columns 28 through 30

4.349897520355098 4.511004835923806 4.672112151492513

Columns 31 through 33

4.833219467061220 4.994326782629927 5.155434098198635

Columns 34 through 36

5.316541413767342 5.477648729336050 5.638756044904757

Columns 37 through 39

5.799863360473465 5.960970676042172 6.122077991610879

Column 40

6.283185307179586

2.3.8 Colon operator in a matrix:-

A matrix A=

>> A=[4 5 7;5 7 9;1 7 4]

A=

4 5 7

5 7 9

20
1 7 4

For example,

>> A(3,:) (Third row of matrix A and its all column)

ans =

1 7 4

The colon operator can also used to extract a submatrix from a matrix A.

>> A(:,1:3)

ans =

4 5 7

5 7 9

1 7 4

>> A(:,2:3)

ans =

5 7

7 9

7 4

2.3.9 Deleting row or column:-


By deleting elements a vector can be made shorter and a matrix can be made to have a
smaller size. For example,

>> V=[2 8 10 56 78 45 34 8 9 3]

V=

2 8 10 56 78 45 34 8 9 3

>> V(2)=[]

V=

2 10 56 78 45 34 8 9 3

>> V(3:9)=[]

V=

21
2 8 3

To delete a row or column of a matrix A, use the empty vector operator, [].

A matrix A=

>> A= [3 5 9;2 7 1;1 9 4]

A=

3 5 9

2 7 1

1 9 4

For example, second row of matrix A is deleted.

>> A(2,:)=[ ](null vector)

A=

3 5 9

1 9 4

Now to restore the deleted row , we use a technique for creating a matrix

>> A=[A(1,:);[2 7 1];A(3,:)]

A=

3 5 9

2 7 1

1 9 4

2.3.10 Dimension:-
To determine the dimension of a matrix or vector, use the command size.

For example,

>> size(A)

ans =

3 3

22
2.3.11 Matrix generators:-
MATLAB provides functions that generates elementary matrices. The matrix of zeros,
the matrix of ones, and the identity matrix are returned by the functions zeros, ones,
and eye, respectively

Table 2.3.11: elementary matrices:

eye (m , n) Returns and m-by-n matrix with 1 on the main diagonal


eye (n) Returns and n-by-n square identity matrix
Zeros (m, n) Return an m-by-n matrix of zeros
Ones (m, n) Return an m-by-n matrix of ones
diag (A) Extracts the diagonal of matrix A
Rand (m, n) Return an m-byn matrix of random numbers

Here are for some examples:

1. >>A =eye (4)

A=

1 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

2. >> B=zeros (2,5)

B=

0 0 0 0 0

0 0 0 0 0

3. >> A=ones(2,4)

A=

1 1 1 1

1 1 1 1

4. >> A=rand(3,3)

A=

23
0.8147 0.9134 0.2785

0.9058 0.6324 0.5469

0.1270 0.0975 0.9575

5. >> a=[1 2 4];

>> diag(a)

ans =

1 0 0

0 2 0

0 0 4

Now create a 5 by 5 matrix in which the middle two rows and middle two columns
are 1s, and the rest of the entries are 0s.

>> S=zeros(5,5)

S=

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

>> S(3:4,:)=ones(2,5)

S=

0 0 0 0 0

0 0 0 0 0

1 1 1 1 1

1 1 1 1 1

0 0 0 0 0

>> S(:,3:4)=ones(5,2)

S=

24
0 0 1 1 0

0 0 1 1 0

1 1 1 1 1

1 1 1 1 1

0 0 1 1 0

25
CHAPTER:-3
ARRAY OPERATIONS AND LINEAR EQUATIONS

3.1 Array operations:-


MATLAB has two different types of arithmetic operations: matrix arithmetic
operations and array arithmetic operations.

3.1.1 Matrix arithmetic operations:-


A MATLAB allow arithmetic operations: +, -, *, /, and ^ to be carried out on
matrices. Thus,

A+B or B+A is valid if A and B are of same size

A*B is valid if As numbers of column equals Bs numbers of rows

A^2 is valid if A is square and equals A*A

For example, using in MATLAB

A= B=

>> A=[2 4 5;8 9 10;3 6 9]

A=

2 4 5

8 9 10

3 6 9

>> B=[20 40 6;8 10 2;4 9 1]

B=

20 40 6

8 10 2

4 9 1

>> A+B

ans =

26
22 44 11

16 19 12

7 15 10

>> A*B

ans =

92 165 25

272 500 76

144 261 39

>> A^2

ans =

51 74 95

118 173 220

81 120 156

>> A-B

ans =

-18 -36 -1

0 -1 8

-1 -3 8

>> A/B

ans =

4.5000 -2.7500 -16.5000

8.0000 -3.8750 -30.2500

8.2500 -5.0625 -30.3750

3.1.2 Array arithmetic operations:-


Array arithmetic operations or array operations for short, are done by element-by-
element. Since the matrix and array operations are the same for addition(+) and
subtraction(-), the character pairs(.+) and (.-) are not used. The list of array operations
is shown below in table 3.1.2.

27
Table 3.1.2: Array operations:
.* Element-by-element multiplication

./ Element-by-element division

.^ Element-by-element exponentiation

For example, using the same 3x 3 matrices,

X= Y=

X=

2 4 5

9 6 10

11 9 8

>> Y=[9 8 11;10 14 1;50 11 2]

Y=

9 8 11

10 14 1

50 11 2

>> X.*Y

ans =

18 32 55

90 84 10

550 99 16

>> X.^2

ans =

4 16 25

81 36 100

121 81 64

28
>> X./Y

ans =

0.2222 0.5000 0.4545

0.9000 0.4286 10.0000

0.2200 0.8182 4.0000

3.2 Solving linear equations:-


A system of linear equations can be written in the form Ax=b

For example, consider the following system of linear equations

The coefficient matrix A is

A= and vector b =

This equation can be solved for x using linear algebra. The result is x= .

Now there are two ways to solve x in MATLAB:

1. x = (use the matrix inverse, inv.)

>> A=[2 4 3;4 3 6;1 2 3]

A=

2 4 3

4 3 6

1 2 3

>> b=[4 5 7]'

b=

29
>> x=inv(A)*b

x=

-4.2000

0.6000

3.3333

2. x =A\b ( to use the backslash (\) operator.)

>> A=[2 4 3;4 3 6;1 2 3];

>> b=[4 5 7]';

>> x=A\b

x=

-4.2000

0.6000

3.3333

3.2.1 Matrix inverse:-


Lets consider a matrix A.

A=

Calculating the inverse of A. here the hand calculation of gives as,

= 1/9

In MATLAB, it becomes as the simple as the following commands:

>> A=[1 2 3;4 5 6;7 8 0]

A=

1 2 3

4 5 6

7 8 0

30
>> inv(A)

ans =

-1.7778 0.8889 -0.1111

1.5556 -0.7778 0.2222

-0.1111 0.2222 -0.1111

Which is similar to the hand calculation of

= 1/9

And determinant of A is

>> det(A)

ans =

27.0000

3.2.2 Matrix functions:-


MATLAB provides a many matrix functions for various matrix/ vector manipulations;

Table 3.2.2: Matrix functions


Det Determinant

Diag Diagonal matrices and diagonals of a matrix

Eig Eigen values and eigenvectors

Inv Matrix inverse

Norm Matrix and vector norms

Rank Number of independent rows or columns

For example,

Example1. Consider the two matrices:

X = Y =

31
Using MATLAB, determine the following:

a) XY

b) X+Y

c)

d)

e)

f)

g)

h)

i) Determinant of X, determinant of Y and determinant of XY.

Solution:

>> X=[40 0 1;20 3 30;-1 10 7]

X=

40 0 1

20 3 30

-1 10 7

>> Y=[10 7 8;3 5 6;1 2 0]

Y=

10 7 8

3 5 6

1 2 0

a) >> X*Y

ans =

401 282 320

239 215 178

27 57 52

b) >> X+Y

32
ans =

50 7 9

23 8 36

0 12 7

c) >> X'

ans =

40 20 -1

0 3 10

1 30 7

d) >> Y'

ans =

10 3 1

7 5 2

8 6 0

e) >> X^2

ans =

1599 10 47

830 309 320

153 100 348

f) >> X'*Y'

ans =

532 214 80

101 75 6

276 195 61

g) >> inv(Y)

ans =

0.1714 -0.2286 -0.0286

33
-0.0857 0.1143 0.5143

-0.0143 0.1857 -0.4143

h) >> X^2+Y^2-2*X*Y

ans =

926 -433 -471

403 -63 18

115 3 264

i)

>> det(X)

ans =

-10957

>> det(Y)

ans =

-70.0000

>> det(X*Y)

ans =

766990

Example2,
Determine the eigenvalues and eigenvectors of A and B using MATLAB

A= B =

Solution:

% Determine the eigenvalues and eigenvectors

>> A=[4 2 -3;-1 1 3;2 5 7]

A=

34
4 2 -3

-1 1 3

2 5 7

>> eig(A)

ans =

0.5949

3.0000

8.4051

>> lamda=eig(A)

lamda =

0.5949

3.0000

8.4051

>> [V,D]=eig(A)

V=

-0.6713 0.9163 -0.3905

0.6713 -0.3984 0.3905

-0.3144 0.0398 0.8337

D=

0.5949 0 0

0 3.0000 0

0 0 8.4051

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

B=

1 2 3

35
8 7 6

5 3 1

>> eig(B)

ans =

11.8655

-2.8655

0.0000

>> lamda=eig(B)

lamda =

11.8655

-2.8655

0.0000

>> [V,D]=eig(B)

V=

0.2657 0.6220 0.4082

0.8910 -0.0285 -0.8165

0.3683 -0.7825 0.4082

D=

11.8655 0 0

0 -2.8655 0

0 0 0.0000

36
CHAPTER:-4
INTRODUCTION TO PROGRAMMING IN MATLAB

4.1 Introduction:-
In these lab sessions, all the commands were executed in the Command Window. The
problem is that the commands entered in the Command Window cannot be saved and
executed again for several times. Therefore, a dierent ways of executing repeatedly
commands with MATLAB is:

1. to create a le with a list of commands,

2. save the le, and

3. run the le.

The les that are used for this purpose are called script les or scripts for short. This
section covers the following topics:

M-File Scripts

M-File Functions

4.2 M-File Scripts:-


A script le is an external le that contains a sequence of MATLAB statements.
Script les have a lename extension .m and are often called M-les. M-les can be
scripts that simply execute a series of MATLAB statements, or they can be functions
that can accept arguments and can produce one or more outputs.

Example1,

Consider the system of equations:

x + 2y + 3z = 1

3x + 3y + 4z = 1

2x + 3y + 3z = 2

Find the solution x to the system of equations.

Solution:-

Use the MATLAB editor to create a le: File New M-le.

Enter the following statements in the script le:

37
A=[1 2 3;3 3 4;2 3 3]

b=[1;1;2]

x=A\b

Now Save the le, for example, example1.m. Run the and change folder, in the
command line, by typing:
>> example1

A=

1 2 3

3 3 4

2 3 3

b=

x=

-0.5000

1.5000

-0.5000

Example 2,

Plot the following cosine functions, y1 = 2cos(x), y2 = cos(x), and y3 = 0.5cos(x),


in the interval 0 x 2. This example has been presented in previous
Chapter(2). Here we put the commands in a le.

Solution:

Enter the following command in the script file.

x = 0:pi/100:2*pi;

y1 = 2*cos(x);

y2 = cos(x);

y3 = 0.5*cos(x);

38
plot(x,y1,'--',x,y2,'-',x,y3,':')

xlabel('0 \leq x \leq 2\pi')

ylabel('Cosine functions')

legend('2*cos(x),cos(x),0.5*cos(x)')

title('Typical example of multiple plots')

axis([0 2*pi -3 3])

Now save the file name example2, run the file ,in the command window, by
typing:

>> example2

39
4.3 M-File functions:-
Functions are programs (or routines) that accept input arguments and return output
arguments. Each M-le function (or function or M-le for short) has its own area of
workspace, separated from the MATLAB base workspace.

Example:
function [fx ] = chapter4(x )
x=6
fx=(x.^4*sqrt(3*x+5))./(x^2+1)^2

Now save the file name factorial, run the file ,in the command window

>> chapter4
x=
6
fx =
4.540100550922778

ans =

4.540100550922778

4.3.1 Anatomy of a M-File function:-


This simple function shows the basic parts of an M-le.

function f = factorial(n)

% FACTORIAL(N) returns the factorial of N.

% Compute a factorial value.

f = prod(1:n);

The rst line of a function M-le starts with the keyword function. It gives the
function name and order of arguments. In the case of function factorial, there are up to
one output argument

As an example, for n = 5, the result is,

function [f ] = factorial(n )
n=5
f = prod(1:n)

end

40
Now save the file name factorial, run the file ,in the command window
>> factorial

n=

f=

120

ans =

120

Function name must begin with a letter, and must be no longer than the maximum of
63 characters. Furthermore, the name of the text le that you save will consist of the
function name with the extension .m. Thus, the above example le would be
factorial.m

4.4 Dierence between scripts and functions:-

Table 4.4:
Scripts Functions

Do not accept input arguments or return Can accept input arguments or return
output arguments. output arguments.

Store variables in a workspace that is Store variables in a workspace internal to


shared with other scripts. the function.

- Are useful for automating a series of Are useful for extending the MATLAB
commands language for your application

Example of Script:- Average of three numbers by using script.


x=10;
y=30;
z=20;
Avg=(x +y +z)/3
Now save the file name average, run the file, in the command window,

>> average

Avg =

20

41
Example of function:- write a function file that convert Fahrenheit to centigrade.
function [C] = FtoC(F)
F=50;
C=(F-32)*5/9
end

Now save the file name fehrn, run the file ,in the command window,
>> fehrn

C=

10

ans =

10

4.5 Input and output arguments:-


As mentioned above, the input arguments are listed inside parentheses following the
function name. The output arguments are listed inside the brackets on the left side.
They are used to transfer the output from the function le. The general form looks like
this

function[outputs] = function_name(inputs)

Function le can have none, one, or several output arguments. Some possible
combinations of input and output arguments.

Table 4.4:- Example of input and output arguments:

function C=FtoC(F) One input argument and one output


argument

Function [h,d]=motion(v,angle) Two input and two argument

4.6 Input to a script le:-


When a script le is executed, the variables that are used in the calculations within the
le must have assigned values. In other words, the variables must be in the
workspace. The assignment value to a value to a variable can be done in the three
ways, depending on the where and how the variable is defined. In case the assignment
of a value to the variable is part of the script file. If the user wants to run the file with

42
a different value, the file must be edited and the assignment of the variable changed,
then, after the file is saved, it can be executed again.

Example:- Suppose there are three subject and the score of three subject and
calculate the average score in three subject.

maths =input(' enter the marks in maths ');


physics =input(' enter the marks in physics ');
chemistry =input(' enter the marks in chemistry ');
Avg= (maths+physics+chemistry)/3

The command prompt when this script file saved as example9 is executed.

>> example9

enter the marks in maths 67

enter the marks in physics 80

enter the marks in chemistry 40

Avg =

62.3333

4.7 Output commands:-


MATLAB automatically generates a display when commands are executed. In
addition to this automatic display, MATLAB has several commands that can be used
to generate displays or outputs.

Two commands that are frequently used to generate output are: disp and fprintf. The
main dierences between these two commands can be summarized as follows (Table
4.7)

Table 4.7: disp and fprintf commands:

Disp Simple to use.


Provided limited control over the appearance of output.

fprintf Slightly more complicated than disp.


Provide total control over the appearance of output.

43
Example of disp command: The script file to calculate the average point scored
in three games.

% the disp command is used to display output.


game1=input('enter the point scored in frist game ');
game2=input('enter the point scored in second game ');
game3=input('enter the point scored in third game ');
avg=(game1+game2+game3)/3
disp(' ')
disp('the average points scored in three games is ')
disp(' ')
disp('avg')

Now save the file name game, run the file, in the command window.
>> game

enter the point scored in frist game 8

enter the point scored in second game 9

enter the point scored in third game 6

avg =

7.6667

the average points scored in three games is

avg

Example of fprintf command: The script file to calculate the average point
scored in three games.

% the disp command is used to display output.


game1=input('enter the point scored in frist game ');
game2=input('enter the point scored in second game ');
game3=input('enter the point scored in third game ');
avg=(game1+game2+game3)/3
fprintf('an average of %f points scored in the three games',avg)

Now save the file name game, run the file, in the command window.
>> game
enter the point scored in frist game 34
enter the point scored in second game 6
enter the point scored in third game 32
avg =
24
an average of 24.000000 points scored in the three games>>

44
Exercises:

1. Write a function le that converts temperature in degrees Fahrenheit (F) to


degrees Centigrade (C). Use input and fprintf commands to display a mix of text
and numbers. Recall the conversion formulation, C = 5/9(F32).

Solution:

function [C ] = FtoC(F )
F=30
C=(F-32)*5/9
fprintf('the temperature in celsius %f is',C)
end

Now save the file name FtoC, run the file, in the command window.

>> FtoC

F=

30

C=

-1.1111

the temperature in celsius -1.111111 is

ans =

-1.1111

2. Write a user-dened MATLAB function, with two input and two output
arguments that determines the height in centimeters (cm) and mass in kilograms
(kg)of a person from his height in inches (in.) and weight in pounds (lb).

(a) Determine in SI units the height and mass of a 5 ft.15 in. person who weight
180 lb.

(b) Determine your own height and weight in SI units.

Solution:

function [cm, kg] = anglo2metric(in,lb)

%1 inch=2.54 centimeters.

%1 pound=0.45359237 kilograms.

cm=in*2.54;

45
kg=lb*0.45359237;
end
>> anglo(75,180)
cm =
190.5000
kg =

81.6462
ans =

190.5000

>> anglo(63,105.8)
cm =
160.0200

kg =

47.9898

ans =

160.0200

46
CHAPTER:-5
CONTROL FLOW AND OPERATORS

5.1 Introduction:-
MATLAB is also a programming language. Like other computer programming
languages, MATLAB has some decision making structures for control of command
execution. These decision making or control ow structures include for loops, while
loops, and if-else-end constructions. Control ow structures are often used in script
M-les and function M-les.

By creating a le with the extension .m, we can easily write and run programs. We do
not need to compile the program since MATLAB is an interpretative (not compiled)
language. MATLAB has thousand of functions, and you can add your own using m-
les.

5.2 Control ow:-


MATLAB has four control ow structures: the if statement, the for loop, the while
loop, and the switch statement.

5.2.1. if statement:-
The simplest form of the if statement is

If expression

statements

end

Now MATLAB supports the variants type of if construct.

1) if ..end

Example of ifend statement is, by using script.

a=4; b=5;c=25;

discr=b*b-4*a*c;

if discr<0
disp('warning: discriminant is negative,root are imaginary');

end

Now save the command and executed in command window.

47
>> discriminant
warning: discriminant is negative,root are imaginary

2) if else..end

Example:

a=45; b=50;

if(a>b)

disp(' a is greater than b');

else
disp('b is grater than a')
end

Now save the command and executed in command window.

>> greater

b is grater than a

3) if..elseif.else.end

Example:

a=4; b=4;

if(a>b)

disp(' a is greater than b');


elseif(a< b)
disp('b is grater than a');
else
disp('a and b are equal');
end

Now save the command and executed in command window.


>> mmmmm

a and b are equal

It should be noted that:

elseif has no space between else and if (one word)

no semicolon (;) is needed at the end of lines containing if, else, end

48
5.2.2 for.end loop:-
In the for ... end loop, the execution of a command is repeated at a xed and
predetermined number of times. The syntax is

for variable = expression

statements

end

Example of for loop using in script file,

for i=1:5;
x=i+3*i-34
end

Now save the command and executed in command window.

>> ccc

x=

-30

x=

-26

x=

-22

x=

-18

x=

-14

5.2.3 while.end loop:-


This loop is used when the number of passes is not specied. The looping continues
until a stated condition is satised. The while loop has the form:

while expression

statements

end

49
Example:
x=2
while x<=11
x=5*x
end

Now save the command and executed in command window.

>> ddd

x=

x=

10

x=

50

5.3 Relational and logical operators:-


A relational operator compares two numbers by determining whether a comparison is
true or false. Relational operators are shown in Table,

Operator Description

> Greater than


< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
~= Not equal to
& AND operator
| OR operator
~ NOT operator

Example: Check the answer with MATLAB.


a)5& 2

b)8 2|6+5&~2

c) 5<=8-3

50
Solution:

a)

>> 5&-2

ans =

b)

>> 8-2|6+5&~2

ans =

c)

>> 5<=8-3

ans =

5.4 Other ow structures:-


The break statement. A while loop can be terminated with the break statement, which
passes control to the rst statement after the corresponding end. The break statement
can also be used to exit a for loop.

The continue statement can also be used to exit a for loop to pass immediately to the
next iteration of the loop, skipping the remaining statements in the loop.

Other control statements include return, continue, switch, etc. For more detail about
these commands, consul MATLAB documentation

51
CHAPTER:-6
DEBUGGING M-FILES

6.1 Introduction:-
This section introduces general techniques for nding errors in M-les. Debugging is
the process by which you isolate and x errors in your program or code. Debugging
helps to correct two kind of errors:

Syntax errors - For example omitting a parenthesis or misspelling a function name.

Run-time errors - Run-time errors are usually apparent and dicult to track down.
They produce unexpected results.

6.2 Debugging process:-


We can debug the M-les using the Editor/Debugger as well as using debugging
functions from the Command Window. The debugging process consists of

Preparing for debugging

Setting breakpoints

Running an M-le with breakpoints

Stepping through an M-le

Examining values

Correcting problems

Ending debugging

6.2.1 Preparing for debugging:-


Here we use the Editor/Debugger for debugging. Do the following to prepare for
debugging:

Open the le

Save changes

Be sure the le you run and any les it calls are in the directories that are on the
search path.

52
6.2.2 Setting breakpoints:-
Set breakpoints to pause execution of the function, so we can examine where the
problem might be. There are three basic types of breakpoints:

A standard breakpoint, which stops at a specied line.

A conditional breakpoint, which stops at a specied line and under specied


conditions.

An error breakpoint that stops when it produces the specied type of warning, error,
NaN, or innite value.

You cannot set breakpoints while MATLAB is busy, for example, running an M-le.

6.2.3 Running with breakpoints:-


After setting breakpoints, run the M-le from the Editor/Debugger or from the
Command Window. Running the M-le results in the following:

The prompt in the Command Window changes to

K>>

Indicating that MATLAB is in debug mode.

The program pauses at the rst breakpoint. This means that line will be executed
when you continue. The pause is indicated by the green arrow.

In breakpoint, we can examine variable, step through programs, and run other
calling functions.

6.2.4 Examining values:-


While the program is paused, we can view the value of any variable currently in the
workspace. Examine values when we want to see whether a line of code has produced
the expected result or not. If the result is as expected, step to the next line, and
continue running. If the result is not as expected, then that line, or the previous line,
contains an error. When we run a program, the current workspace is shown in the
Stack eld. Use who or whos to list the variables in the current workspace.

6.2.5 Correcting and ending debugging:-


While debugging, we can change the value of a variable to see if the new value
produces expected results. While the program is paused, assign a new value to the
variable in the Command Window, Workspace browser, or Array Editor. Then
continue running and stepping through the program.

53
6.2.6 Ending debugging:-
After identifying a problem, end the debugging session. It is best to quit debug mode
before editing an M-le. Otherwise, you can get unexpected results when you run the
le. To end debugging, select Exit Debug Mode from the Debug menu.

6.2.7 Correcting an M-le:-


To correct errors in an M-le,

Quit debugging.

Do not make changes to an M-le while MATLAB is in debug mode.

Make changes to the M-le.

Save the M-le.

Clear breakpoints.

Run the M-le again to be sure it produces the expected results.

54
ASSIGNMENT NO:-1
PART - 1

Question 1:- Start MATLAB.

Solution:- Loging into your account. You can enter MATLAB by double clicking on
the MATLAB shortcut icon on your window desktop. When you start matlab, a special
window called the matlab desktop appears. The major tools within from the desktop are:-

Command window
Command history
Workspace
Current directory
Help browser
Start button
Question 2:- Enter the following.
1+2

x= 1+2

x= 1+2;

y= x^2+2*x+8

Solution:-
>> 1+2

ans =

>> x=1+2

x=

>> x=1+2;

>> y=x^2+2*x+8

y=

55
23

Question 3:- Enter the following


Format long e

pi
You can use the arrow keys and the delete key to recall and edit previous commands.
Press the up arrow key twice to recall the format command and delete the e and
press enter. Then display pi again. Repeat with the following formats.

Format short e

Format short

Solution:-
>>format long e

>>pi

ans =

3.141592653589793e+00

>>format long

>>pi

ans =

3.141592653589793

>>format short e

>>format short

Question 4:- Enter the following


a = pi/6

sin(a)^2+cos(a)^2

exp(2*log(3)+3*log(2))

solution:-
>> a=pi/6

56
ans=

0.5236

>>sin(a)^2+cos(a)^2

ans =1

>>exp(2*log(3)+3*log(2))

ans =

72.0000

Question 5:- Enter the following


a = [1 2 3]

b = [4 5 6]

Z = a + i *b

i here is the square root of -1.

You can use j instead if that is what you are use to.

Solution:-
>> a=[1 2 3]

a=

1 2 3

>> b=[4 5 6]

b=

4 5 6

>> Z=a+i*b

Z=

1.0000 + 4.0000i 2.0000 + 5.0000i 3.0000 + 6.0000i

Question 6:- Display the real and imaginary parts of Z and the conjugate of Z.

Solution:-
>>real(Z)

ans =
57
1 2 3

>>imag(Z)

ans =

4 5 6

>>conj(Z)

ans =

1.0000 - 4.0000i 2.0000 - 5.0000i 3.0000 - 6.0000i

Question 7:- Display the magnitude and angle of Z.

Solution:-
>>abs(Z)

ans =

4.1231 5.3852 6.7082

>>angle(Z)

ans =

1.3258 1.1903 1.1071

Question 8:- Try the following.


Z

Z.

Solution:-
>>Z'

ans =

1.0000 - 4.0000i

2.0000 - 5.0000i

3.0000 - 6.0000i

>> Z.'

58
ans =

1.0000 + 4.0000i

2.0000 + 5.0000i

3.0000 + 6.0000i

Question 9:- Enter the two matrices

A= B=

Solution:-
>> A=[1 2;3 4]

A=

1 2

3 4

>> B=[5 6;7 8]

B=

5 6

7 8

Question 10:- Try the following and ensure you can follow what is happening.
A+5

A+B

A-B

A*B

A^2

Solution:-
>>A+5

ans =

6 7

59
8 9

>>A+B

ans =

6 7

10 12

>>A-B

ans =

-4 -4

-4 -4

>>A*B

ans =

19 22

43 50

>>A^2

ans =

7 10

15 22

>>A'

ans =

1 3

2 4

Question 11:- Solve the simultaneous equation on page 15 of the notes. A


should already be present from exercise 10.

b = [5;11]

x = A/b

60
Now check that x is the correct solution.

A*x

Solution:-
>> b=[5;11]

b=

11

>> x=A\b

x=

>>A*x

ans =

11

Question 12:- It is just as easy to solve a hundred simultaneous equations in a


hundred variables. First create a 100 by 100 matrix of random numbers.

A1 = rand(100);

If you forget to put in the semicolon, 10,000 numbers will be printed out.

Next create a column vector with 100 numbers

b = (1:100)

Now solve

x = A1/b

Check the solution is correct.

A1*x

Solution:-
>> A1 =rand(100);

61
>> b1=(1:100)'

b1 =

1 11 21 31 41 51 61 71 81 91

2 12 22 32 42 52 62 72 82 92

3 13 23 33 43 53 63 73 83 93

4 14 24 34 44 54 64 74 84 94

5 15 25 35 45 55 65 75 85 95

6 16 26 36 46 56 66 76 86 96

7 17 27 37 47 57 67 77 87 97

8 18 28 38 48 58 68 78 88 98

9 19 29 39 49 59 69 79 89 99

10 20 30 40 50 60 70 80 90 100

>> x=A1\b1

x=

-22.6573 -293.4187 155.9501 33.8742 -38.3632

-9.4224 74.5211 -231.0299 120.7708 -124.8291

408.7460 -50.6260 48.8437 241.8894 212.7490

-49.9136 -23.4276 18.8508 194.0674 -92.6644

-29.4240 -274.1647 95.0389 -102.7774 35.8517

34.0066 -30.2757 -155.5093 290.0812 251.2868

-225.0390 -214.8763 398.6338 -326.0107 2.1678

57.2000 -0.4152 -305.9743 18.3732 133.6073

145.4533 73.1540 12.3459 -68.6404 8.1115

-44.0289 -96.6767 72.4688 337.7343 249.6340

46.0152 60.8013 239.9429 36.5235 27.4000

-67.1376 142.6462 -279.3884 -35.0004 -139.8051

-113.4862 -18.1303 -183.4062 -60.1430 165.4769

62
325.7246 128.6720 99.5035 85.2169 -81.5710

-88.6461 -114.3948 311.9056 -270.4036 175.7644

-125.0013 38.9230 -64.9782 -113.0028 -148.4110

-300.4700 183.4621 162.4804 110.3110 -152.8604

-373.1792 -33.0242 -98.0830 24.0109 -111.1144

235.3449 -32.9869 -36.8006 10.1050 -315.8545

-17.6080 96.4091 -61.8856 -17.9100 -12.6657

>> A1*x

ans =

1.0000 19.0000 37.0000 55.0000 73.0000

2.0000 20.0000 38.0000 56.0000 74.0000

3.0000 21.0000 39.0000 57.0000 75.0000

4.0000 22.0000 40.0000 58.0000 76.0000

5.0000 23.0000 41.0000 59.0000 77.0000

6.0000 24.0000 42.0000 60.0000 78.0000

7.0000 25.0000 43.0000 61.0000 79.0000

8.0000 26.0000 44.0000 62.0000 80.0000

9.0000 27.0000 45.0000 63.0000 81.0000

10.0000 28.0000 46.0000 64.0000 82.0000

11.0000 29.0000 47.0000 65.0000 83.0000

12.0000 30.0000 48.0000 66.0000 84.0000

13.0000 31.0000 49.0000 67.0000 85.0000

14.0000 32.0000 50.0000 68.0000 86.0000

15.0000 33.0000 51.0000 69.0000 87.0000

16.0000 34.0000 52.0000 70.0000 88.0000

17.0000 35.0000 53.0000 71.0000 89.0000

18.0000 36.0000 54.0000 72.0000 90.0000

63
91.0000

92.0000

93.0000

94.0000

95.0000

96.0000

97.0000

98.0000

99.0000

100.0000

64
PART-2
Question 1:- You should have the two matrices

A= B=

From exercise 10 in part 1. If not, then enter them again.

Solution:-
>>A=[1 2;3 4]
A=

1 2

3 4

>> B=[5 6;7 8]

B=

5 6

7 8

Question 2:- Now try the following array operations.


A.*B

A./B

A.^B

Sin(A*pi/6)

D=A.^2

Sqrt(D)

Clear the workspace of all variables.

Clear

Solution:-
>> A.*B

ans =

5 12

65
21 32

>> A./B

ans =

0.2000 0.3333

0.4286 0.5000

>>A.^B

ans =

1 64

2187 65536

>>sin(A*pi/6)

ans =

0.5000 0.8660

1.0000 0.8660

>> D=A.^2

D=

1 4

9 16

>>sqrt(D)

ans =

1 2

3 4

Question 3:- Plot the polynomial 2x3-x


x = linspace(-1,1,100);

y = 2*x.^3-x;

What happens if you dont include the dot?

Plot (x,y)

Dont close the figure containing the plot.

66
Solution:-
>> 2*x^3-x

ans =

51

>> x=linspace(-1,1,100);

>> y=2*x.^3-x;

>> plot(x,y)

>> 4*x^3-3*x

Question 4:- Plot the polynomial 4x3-3x using the function polyval. First find
out how to use polyval using the help.

Doc polyval

p=[4 0 -3 0]

y1=polyval(p,x);

hold on

plot (x,y1,g)

67
Solution:-
>> x=linspace(-1,1,100);

>> p=[4 0 -3 0]

p=

4 0 -3 0

>> y1=polyval(p,x);

>> plot(x,y1,'g')

Question 5:- There are many functions that handle polynomials. Look them up
in the help. Enter doc polyval again, then click on polynomials on the path at the
top of the page. What does the function roots do?

Solution:-
roots returns a column vector whose elements are the roots of the given polynomial.

Question 6:- Plot the roots of the polynomial on to the graph.


r = roots(p)

ry = zeros(3,1)

The plot should still be held from exercise 4.

68
Plot (r, ry,rx)

Clear the fig.

clf

Solution:-
>> r=roots(p)

r=

0.8660

-0.8660

>> ry=zeros(3,1)

ry =

>> plot(r,ry,'rx')

69
Question 7:- Enter the following .
a=2:0.5:4

a(2)

a([2 4])

a(2:4)

a(2:end)

Solution:-
>> a=2:0.5:4

a=

2.0000 2.5000 3.0000 3.5000 4.0000

>>a(2)

ans =

2.5000

>>a([2 4])

ans =

2.5000 3.5000

>>a(2:4)

ans =

2.5000 3.0000 3.5000

>>a(2:end)

ans =

2.5000 3.0000 3.5000 4.0000

Question 8:- Enter the following


w =(1:5)*(5:10)

This produce a 5 by 6 matrix that we can use in the next exercise.

Set the 3rd element on the 2nd row of w to 100.

Solution:-
70
>>a(2)

ans =

2.5000

>>a([2 4])

ans =

2.5000 3.5000

>>a(2:4)

ans =

2.5000 3.0000 3.5000

>>a(2:end)

ans =

2.5000 3.0000 3.5000 4.0000

>> w=(1:5)'*(5:10)

w=

5 6 7 8 9 10

10 12 14 16 18 20

15 18 21 24 27 30

20 24 28 32 36 40

25 30 35 40 45 50

>>w(2,3)=100

w=

5 6 7 8 9 10

10 12 100 16 18 20

15 18 21 24 27 30

20 24 28 32 36 40

25 30 35 40 45 50

71
Question 9:- Enter the following
w(2:4,2:4)

w(2,:)

w(:,5)

w([1 5],[2,4])

w(:)

w(:)=1:30

Solution:-
>>w(2:4,2:4)

ans =

12 100 16

18 21 24

24 28 32

>>w(2,:)

ans =

10 12 100 16 18 20

>>w(:,5)

ans =

18

27

36

45

>>w([1 5],[2,4])

ans =

6 8

30 40

72
>>w(:)

ans =

10

15

20

25

12

18

24

30

100

21

28

35

16

24

32

40

18

27

36

45

73
10

20

30

40

>> w(:)=1:30

W= 1 6 11 16 21 26

2 7 12 17 22 27

3 8 13 18 23 28

4 9 14 19 24 29

5 10 15 20 25 30

74
Question 10:- By now you should have a nice collection of variables. Try
Who

Whos

You will also be able to see your variables in the workspace window.

Enter the following in the command window.

Save

Clear

All variables should have been saved to matlab.mat. If you cant see this in the
Current Folder window, right click in the window and select refresh.

The workspace window should be empty. Double click on matlab.mat to restore


all your variables.

Solution:-
>>who

Your variables are:

a a1 ans b b1 d g p q r ry w x y y1 z

>>whos

Name Size Bytes Class Attributes

a 1x5 40 double

a1 100x100 80000 double

ans 30x1 240 double

b 2x2 32 double

b1 100x1 800 double

d 2x2 32 double

g 99x1 1584 double complex

p 1x4 32 double

q 1x4 32 double

r 3x1 24 double

ry 3x1 24 double
75
w 5x6 240 double

x 1x100 800 double

y 1x100 800 double

y1 1x100 800 double

z 1x3 48 double complex

Question 11:- Produce and a script called graph.


edit graph

In graph enter

x = linspace(-2*pi,2*pi,100);

y = sin(x);

plot(x,y)

grid

Save by clicking on the icon and run by entering

graph

in the command window.

Solution:-
x = linspace(-2*pi,2*pi,100);
y = sin(x);
plot(x,y)

76
Question 12:- Add the following at the end of script created above.
hold on

y1=mysin(x);

plot(x,y1,r:)

axis([-2*pi,2*pi,-2,2])

click on the save and run icon.

Solution:-
x = linspace(-2*pi,2*pi,100);
y = sin(x);
plot(x,y)
y1 = mysin(x);
plot(x,y1,'r:')
axis([-2*pi,2*pi,-2,2])

77
Question 13:-You should have a file called mysqrt.m. Edit this file
Edit mysqrt

function x =mysqrt(A)

% My square root function.

% x = mysqrt(A)

% x is the square root of A.

X=1; % First guess

err = 1; % set error to something to get started

while (err>0.0001)

x=myfunction(A,x); % call to local function below

err=abs(A x.^2); %calculate the error

end

78
function y=myfunction(A,x)

% Local function to calculate the

% Newton Raphson Iteration equation

Y=(x.^2+A)./(2*x);

Test the function by enter the following into the command window.

mysqrt(9)

mysqrt(2)

help mysqrt

Solution:- No help found for mysqrt.m.

Question 15:- Enter the following


degrees = 0:6:360;

rad = degrees*pi/180;

plot (sin(rad))

Close the graph ans repeat the first two commands by double clicking on them
in the Command History window.

Solution:-
>> degrees = 0:6:360;

>> rad = degrees*pi/180;

>> plot(sin(rad))

79
Question 16:- Drag the plot command from the Command History into the
command window and change it to:-

plot(degrees,sin(rad))

See how the plot changes.

Solution:-
>> degrees = 0:6:360;

>> rad = degrees*pi/180;

>> plot(degrees,sin(rad))

80
Question 17:- Hold down control and select each of the following
commands in the command history window,

degrees = 0:6:360;

rad = degrees*pi/180;

plot(degrees,sin(rad))

Then press the right mouse button and select create script.

Save the file as graph1.m

Solution:-
degrees = 0:6:360;

rad = degrees*pi/180;

plot(degrees,sin(rad))

81
Question 18:- Annotate the graph by adding the following lines to the script.
axis([0 360 -1 1])

title(sine wave)

xlabel(degrees)

ylabel(value)

grid

Observe the resulting graph.

Solution:-
degrees=0:6:360;

rad=degrees*pi/180;

plot(degrees,sin(rad))

axis ([0 360 -1 1])

title( 'sine wave')

xlabel ('degrees')

82
ylabel ('value')

grid

Question 19:- Change the title and the plot command so that a cosine wave is
plotted in green. Save as graph2.

Solution:-
degrees=0:6:360;

rad=degrees*pi/180;

plot(degrees,cos(rad),'g')

axis([0 360 -1 1])

title('cos wave')

xlabel('degrees')

ylabel('value')

grid
83
Question 20:- Change the title and the plot command so that tan is plotted in
red. Change the y limit to -10 to 10. Save as graph3.

Solution:-

degrees=0:6:360;

rad=degrees*pi/180;

plot(degrees,tan(rad),'r')

axis([0 360 -10 10])

title('tan wave')

xlabel('degrees')

ylabel('value')

grid

84
85
PRACTICAL ASSIGNMENT

Question 1:- Find a short MATLAB expression to built the matrix

b=

Solution:-
>>b = [1:7;9:-2:-3;2.^(2:8)]

b=

1 2 3 4 5 6 7

9 7 5 3 1 -1 -3

4 8 16 32 64 128 256

Question2:- Give a MATLAB expression that uses only a single matrix


multiplication with b to obtain

a) The sum of columns 5 and 7 at b.

Solution:-
>> b*[0 0 0 0 1 0 1]'

ans =

12

-2

320

b) The last row of b.

Solution:-
>> [0 0 1]*b

ans =

4 8 16 32 64 128 256

c) A version of b with rows 2 and 3 swapped.

86
Solution:-
>> [1 0 0;0 0 1;0 1 0]*b

ans =

1 2 3 4 5 6 7

4 8 16 32 64 128 256

9 7 5 3 1 -1 -3

Question3:- Give a MATLAB expression that multiplies two vectors to obtain


a) the matrix

Solution:-
>> [1 1 1]'*(1:5)

ans =

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

b) the matrix

Solution:-
>> (0:4)'*[1 1 1]

ans =

0 0 0

1 1 1

2 2 2

3 3 3

87
4 4 4

Question 4:- Create the following matrix A


1 2 3 4 5 6 7

A= 11 12 12 13 14 5 6

9 10 16 18 19 20 21

22 23 24 25 26 27 28

a) Create a 3*4 matrix b from the 1st , 3rd and 4th rows and the 1st , 3rd , 5th
and 7th columns of the matrix A.

Solution:-
>> B=A ([1 3 4],[1 3 5 7])

B=

1 3 5 7

9 16 19 21

22 24 26 28

b) Create a 15 elements long row vector u from the elements of the 3rd row and
the 5th and 7th columns of matrix A.

Solution:-
>> u = [A(3,:) A(17:20) A(25:28)]

u=

9 10 16 18 19 20 21 5 14 19 26 7 6 21 28

88
ASSIGNMENT NO:-2
Question paper of Test-1

PART -1

Question1:-

a) Compute , 2 + in command window.

Solution:-
>> 2+(3+4/5)/(5+3/4)

ans =

2.6609

b) Choose the most appropriate word from the options given below to complete
the following sentence:

A pair of single right quote () is used to enclose

1) Character string

2) Command line

3) Title of a command

4) All of these

Solution:-
1) Character string.

c) Create a row vector that has the elements: 32, 4, 81, , 63, cos ( ).

Solution:-

>> [32 4 81 exp(2.5) 63 cos(pi/3)]


ans =

32.0000 4.0000 81.0000 12.1825 63.0000 0.5000

89
d) Determine how long it takes light to travel to earth from a star 1 million miles
away. The speed of light is 3* m/s. Calculate the problem in command
window using MATLAB.

Solution:-
>> d=1609344000;

>> s=3*10^8;

>> t=d/s

t=

5.3645

e) Create two (3*4) Matrices and use a MATLAB command to add the matrices
element by element.

Solutions:-
>> A=[1 2 3 4;5 6 7 8;9 10 11 12]

A=

1 2 3 4

5 6 7 8

9 10 11 12

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

B=

5 6 7 8

9 1 4 6

6 5 4 2

>> A+B

ans =

6 8 10 12

14 7 11 14

15 15 15 14

90
PART- 2

Question2:- Create the following matrix A = . Use

the matrix A to:

a) Create a five element row vector named va that contains the elements of the
second row of A.

b) Create a three element row vector vb that contains the elements of the fourth
column of A.

c) Create a ten element row vector named vc that contains the elements of the
first and second rows of A.

d) Create a six element row vector named vd that contains the elements of the
second and fifth column of A.

Solution:-
>> A=[6 43 2 11 87;12 6 34 0 5;34 18 7 41 9]

A=

6 43 2 11 87

12 6 34 0 5

34 18 7 41 9
a)
>> va=A(2,:)

va =

12 6 34 0 5

b) >> vb=[A(10:12)]

vb =
11 0 41

c) >> vc=[A(1,:) A(2,:)]

vc =

6 43 2 11 87 12 6 34 0 5

91
d) >> vd=[A(4:6) A(13:15)]

vd =

43 6 18 87 5 9

Question3:- A trigonometric identity is given by

cos2

Verify that the identity is correct by calculating each side of the equation,
substituting

x=

Solution:-
- >> x=pi/5;

>> LHS=(cos(x/2))^2

LHS =

0.9045

>> RHS=(tan(x)+sin(x))/(2*tan(x))

RHS =

0.9045

92
PART-3

Qustion4:-
a) The coefficient of friction, can be determined by the experiment by
measuring the force F required to move a mass m. When F is measured and m is
known, the coefficient of friction can be calculated by = F/(mg) (g = 9.81 m/s2).

Results from measuring F in six tests are given in the table below. Determine the
coefficient of friction in each test, and the average from all tests. (In command
window)

Test # 1 2 3 4 5 6
Mass m 2 4 5 10 20 50
(kg)
Force F 12.5 23.5 30 61 117 294
(N)

Solution :-

>> g=9.81;
>> mass=[2 4 5 10 20 50]

mass =

2 4 5 10 20 50

>> force=[12.5 23.5 30 61 117 294]

force =

12.5000 23.5000 30.0000 61.0000 117.0000 294.0000

>> mv=force./(mass*g)

mv =

0.6371 0.5989 0.6116 0.6218 0.5963 0.5994

>> avg=mean(mv)

avg =

0.6109

93
b) Use matrix operations to solve the following system of linear equations.

4 x 2 y + 6z = 8

2x+8y+2z=4

6 x + 10 y + 3 z = 0

Solution:-
>> A=[4 -2 6;2 8 2;6 10 3];

>> b=[8;4;0];

>> X=inv(A*b)

X=

-1.8049

0.2927

2.6341

94
ASSIGNMENT NO:-3

Question 1:-Write a user-defined MATLAB function, with two input and two
output arguments that determines the height in centimeters and mass in
kilograms of a person from his height in inches and weight in pounds. For the
function name and arguments use [cm, kg] = STtoSI (in, lb). The input
arguments are the height in inches and weight in pounds, and the output
arguments are the height in centimeters and mass in kilograms. Use the function
in the Command Window to:

a) Determine in SI units the height and mass of a 5 ft 10in. person who weighs
175 lb.

b) Determine your own height and weight in SI units.

Solution:-
function [cm,kg ] = STtoSI(in,lb)
cm=in*2.54
kg=lb*0.45359

end
>> STtoSI(70,175)

cm =
1.778000000000000e+02
kg =
79.378249999999994
ans =
1.778000000000000e+02

>> STtoSI(63,105.8)
cm =
1.600200000000000e+02

kg =
47.989821999999997
ans =
1.600200000000000e+02

95
Question 2:- Write a user-defined MATLAB function for the following math
function:

y(x) = 0.9 12 5x

The input to the function is x and the output is y. Write the function such that x
can be a vector (use element-by-element operations).

a) Use the function to calculate y(3), and y(5).

b) Use the function to make a plot of the function y(x) for -4 x 4.

Solution:-
function y = math_func(x)
y = 0.9*x.^4+12*x.^2-5*x
Now save it as math_func.m. call the function in command window,
>>math_func
>> x=[-3 5]
x=
-3 5
>> y=math_func(x);
y=
195.9000 837.5000

>> plot(x,math_func(x))
y=
195.9000 837.5000
>> title('function=0.9*x.^2-12*x.^2-5*x')
>> xlabel('x-axis')
>> ylabel('y-axix')

96
Question 3:- Write a user-defined MATLAB function for the following math
function:

r( ) = 2 (1.1 - )

The input to the function is (in radians) and the output is r. Write the function
such that can be a vector.

a) Use the function to calculate r(/3) and r(3/2).

b) Use the function to plot (polar plot) r( ) for 0 2 .

Solution:-
function r = math_func2(theta)
r = 2*(1.1-sin(theta).^2)
Now save it as math_func.m. call the function in command window,
>> math_func2
>> theta=[pi/3 3*pi/2];
>> r=math_func2(theta);
r=

97
0.7000 0.2000
>> theta=0:0.01:2*pi;
>> plot(theta,math_func2(theta));
>> title('r(theta)=2*(1.1-sin(theta)^2')
>> xlabel('x-axis')
>> ylabel('y-axis')

Question 4:- Write a user-defined MATLAB function that calculates the local
maximum or minimum of a quadratic function of the form: f(x) = a + bx + c.
For the function name and arguments use [x, y] = maxmin (a, b, c). The input
arguments are the constants a, b, and c, and the output arguments are the
coordinates x and y of the maximum or the minimum.

Use the function to determine the maximum or minimum of the following


functions:

a) f(x) = 3 - 18x + 48
b) f(x) = -5 + 10x 3

Solution:-
function [x,y] = maxmin(a,b,c )

98
x=-b/2*a
y=a*x^2+b*x+c

end

>> maxmin(3,-18,48)

x=

27

y=

1749

ans =

27

>> maxmin(-5,10,-3)

x=

25

y=

-2878

ans =

25

Question 5:- The value P of a savings account with an initial investment of ,


and annual interest rate r (in %), after t years is:

P= ( )

Write a user-defined MATLAB function that calculates the value of a savings


account. For the function name and arguments use P = saval (PO, r, t). The
inputs to tha function are the initial investment, the interest rate, and the
number of years. The output is the value of the account. Use the function to
calculate the value of a $10,000 investment at an annual interest rate of 6% after
13 years.

Solution:-
function [ P ] = savall(PO,r,t )
P = PO*(1+r/100)^t
end

99
>> savall(10000,6,13)

P =
2.1329e+04

ans =
2.1329e+04

Question 6:- Write a user-defined MATLAB function that converts torque


given in units of lb-in. to torque in units of N-m. For the function name and
arguments use Nm = lbintoNm (lbin). The input argument is the torque in lb-in.,
and the output argument is the torque in N-m. Use the function to convert 500
lb-in. to units of N-m.
Solution:-
function [Nm] = lbintoNm (lbin)
torque = 0.11298482*lbin

end
>> lbintoNm(500)

torque =

56.4924

Question 7:- Write a user-defined MATLAB function that determines the area
of a triangle when the lengths of the sides are given. For the function name and
arguments use [Area] = triangle(a,b,c). Use the function to determine the areas of
triangles with the following sides:

(a) a = 10, b = 15, c = 7.


(b) a = 6, b = 8, c = 10.
(c) a = 200, b = 75, c = 250.

Solution:-
function [al,bet,gam] = trianglee(a,b,c )
al=inv(cos((b^2+c^2-a^2)/(2*b*c)))
bet=inv(cos((c^2+a^2-b^2)/(2*a*c)))
gam=inv(cos((a^2+b^2-c^2)/(2*a*b)))

end

>> trianglee(10,15,7)

100
al =
1.4794
bet =
1.1679
gam =
1.6507
ans =
1.4794
>> trianglee(6,8,10)
al =
1.4353
bet =
1.2116
gam =

1
ans =
1.4353
>> trianglee(200,75,250)
al =
1.3667
bet =
1.7658
gam =
1.1821
ans =
1.3667

Question 8:- Evaluate the following expressions without using MATLAB.


Check the answer with MATLAB.

a) 5 < = 8 3
b) y = 7 < 3 1 + 6 > 2
c) y = (7 < 3) 1 + (6 > 2)
d) y = 2 4+5==7+

Solution:-

a) 5<=8-3
5<= 5 which is true

Ans=1

To check in MATLAB,

>> 5<=8-3

101
ans =

b) y = 7 < 3 1 + 6 > 2

7<3 false

=0

6>2 true

=1

i.e -1+1=0

=0

In MATLAB,

>> y = 7<3-1+6>2

y=

c) y = (7 < 3) 1 + (6 > 2)

=0

In matlab,

>> y = (7<3)-1+(6>2)

y=

d) y = 2 4+5==7+

=13==12 which is false

=0

In MATLAB,

>> y = 2*4+5==7+20/4

y=

102
Question 9:- Given: a = 10, b = 6. Evaluate the following expressions without
using MATLAB. Check the answer with MATLAB.

a) y = a > = b
b) y = a b < =
c) y = a - ( )

Solution:-
a) y = a > = b

y=10>=6 true

y=1

In MATLAB,

>> a = 10; b = 6;

>> y = a>=b

y=

b) y = a b < =

y=10-6<=6/2=4<3 false

y=0

In MATLAB,

>> y = a-b<=b/2

y=

c) y = a - ( )

y=10-(6<=6/2) = 10-(6<=3)

10-0=10

y=10

In MATLAB,

>> a=10;b=6;

103
>> y = a-(b<=b/2)

y=

10

Question 10:- Given: v = [4 2 1 5 0 1 3 8 2]and w = [0 2 1 1 0 2 4


3 2]. Evaluate the following expressions without using MATLAB. Check the
answer with MATLAB.

a) v > = w
b) w ~ = v

Solution:-
a) v > = w

v = [4 -2 -1 5 0 1 -3 8 2], w = [0 2 1 -1 0 -2 4 3 2]

v>=w

1 0 0 1 1 1 0 1 1

b) w~ =v

1 1 1 1 0 1 1 1 0

Question 11:- Use the vectors v and w from the previous problem. Use
relational operators to create a vector y that is made up of the elements of w that
are greater than the elements of v.

Solution:-
v = [4 -2 -1 5 0 1 -3 8 2], w = [0 2 1 -1 0 -2 4 3 2]

w>v

0 1 1 0 0 0 1 0 0

Question 12:- Evaluate the following expressions without using MATLAB.


Check the answer with MATLAB.

a) 5& 2
b) 8 2|6+5&~2
c) ~(4&0)+8*~(4|0)

104
Solution:-
a) 5&-2

=1

b) 8-2|6+5&~2

=1

c) ~(4&0)+8*~(4|0)

=1

Question 13:- The maximum daily temperature (in F) for New York City and
Anchorage, Alaska during the month of January, 2001 are given in the vectors
below (data from the U.S. National Oceanic and Atmospheric Administration).

TNY = [31 26 30 33 33 39 41 41 34 33 45 42 36 39 37 45 43 36 41 37 32 32 35 42 38
33 40 37 36 51 50]

TANC = [37 24 28 25 21 28 46 37 36 20 24 31 34 40 43 36 34 41 42 35 38 36 35 33
42 42 37 26 20 25 31]

Write a program in a script file to answer the following:

a) Calculate the average temperature for the month in each city.

b) How many days was the temperature below the average in each city?

c) How many days, and which dates in the month, was the temperature in
Anchoragehigher than the temperature in New York?

d) How many days, and which dates in the month, was the temperature in both
cities above freezing (above 30 F)?

Solution:-
TNY = [31 26 30 33 33 39 41 41 34 33 45 42 36 39 37 45 43 36 41 37 32 32 35 42 38
33 40 37 36 51 50];

TANC = [37 24 28 25 21 28 46 37 36 20 24 31 34 40 43 36 34 41 42 35 38 36 35 33
42 42 37 26 20 25 31];
avgofTNY = mean(TNY)
avgofTANC = mean(TANC)
TNYbelow37 = TNY <= 37;

105
NdaysTNYbelow37 = sum(TNYbelow37)
TANCbelow33 = TANC <=33;
NdaysTANCbelow33 = sum(TANCbelow33)
Z = TANC > TNY;
NdaysZ = sum(Z)
datesZ = find(Z)
P = (TNY == TANC);
NdaysP = sum(P)
datesP = find(P)
days = sum(TNY>32&TANC>32)
dates = find((TNY>=32)&(TANC>=32))

>> temp1
avgofTNY =
37.6774
avgofTANC =
33.1290
NdaysTNYbelow37 =
17
NdaysTANCbelow33 =
13
NdaysZ =
11
datesZ =
1 7 9 14 15 18 19 21 22 25 26
NdaysP =
1
datesP =
23
days =
16
dates =
7 8 9 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

106
107

You might also like