Sunteți pe pagina 1din 96

CHAPTER - 1

Starting with MATLAB

Start MATLAB: 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

Using MATLAB as a calculator:

For example: lets suppose you want to calculate the expression in


command window, (4+3)*7

>> (4+3)*7

ans =

49

You may assign a value to a variable or argument name.

For example: S = 4+3*7

>> S=4+3*7

S=

25

Using arithmetic operator in command window:

a) Addition:
for example R = 9+5+3

>> R=9+5+3

R=

17

1
b) Subtraction:

For example P=5-9

>> P=5-9

P=

-4

c) Multiplication:

For example C= 15*6

>> C=15*6

C=

90

d) Division:

For example A= 84/6

>> A=84/6

A=

14

Lets consider the arithmetic operation, but we will include


parentheses.

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

>> (7+5)*9

ans =

108

Now, parentheses are missing: 7+5*9

>> 7+5*9

ans =

52

2
By adding parentheses, these two expression give different results:
108 and 52.

Now consider example:

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

In MATLAB, it becomes

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

ans =

0.5060

If parentheses are missing,

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

ans =

3.5810

Creating MATLAB variables:

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= 3+4*8-4

>> x=3+4*8-4

x=

31

Overwriting variable:

3
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.

For example

>>A=153;

>>A=A+2

A=

152

Error message:

If we enter an expression incorrectly, MATLAB will return an error message.


For example, in the following, we left out the multiplication sign,*, in the
following expression

>> T=10;

>> 5T

5T

|Error: Unexpected MATLAB expression.

Controlling the appearance of floating point number:

>>format short

>> x=-163.6667

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

>>format long

>> x= -1.636666666666667e+002

Entering multiple statement per line:

For example,

>> r=5; b=cos(r),c=sin(r)

4
b=

0.2837

c=

74.2099

CHAPTER-2
Creating Arrays and Basic plotting

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

5
Example:

The value of expression y = sin(x) +10y, for p = 5, v= 2, and s = 8 is


computed by

>> p=5;

>> v=2;

>> s=8;

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

z=

28.2904

The subsequent examples are

>>log(752)

ans =

6.6227

>>log10(752)

ans =

2.8762

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


enter the following command in MATLAB.

>> i= sqrt (-1)

i=

0 + 1.0000i

>>sin(i)

ans =

0 + 1.1752i

>>exp(inf)

ans =

6
Inf

>> 1^inf

ans =

NaN

>> x=1/0

x=

Inf

>> y= cos(1/0)

y=

NaN

>>exp(10)

ans =

2.2026e+04

Basic plotting:

Creating simple plots:

The Matlab command to plot a graph is plot(x,y) vectors v=(2,3,5,7,2,9) and


s=( 3,- 1,4,6,4,6)

>>v=[2 3 5 7 2 9];

>> s=[3 -1 4 6 4 6];

>>plot(v, s)

7
6

-1
2 3 4 5 6 7 8 9

Creating a Sine wave (one dimensional plot):

To create a Sine wave in Matlab command window.

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

>>y=sin(x);

>>plot (x,y)

8
1

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0
0 0.5 1 1.5 2 2.5 3 3.5

Create a two dimensional plot:

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

>> y=tan(x);

>> z=cos(x);

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

>> hold

Current plot held

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

9
80

60

40

20

-20

-40

-60

-80
0 1 2 3 4 5 6 7

Create a three dimensional plot:

>> 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:')

10
80

60

40

20

-20

-40

-60

-80
0 1 2 3 4 5 6 7

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')

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

Specifying line style and colors:

Symbol Color Symbol Line Symbol Marker


Style
k black - Solid + Plus
r red -- Dashed sign
b blue : Dotted o Circle
g green -. Dash- * Asterisk
c cyan dot . Point
m None No line s Square
magenta d
y yellow Diamond

12
Entering a vector (One-dimensional array):

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 x,

>>a= [3 4 5 6 7]

x=

34567

To enter a column vector, y,

>> y= [3;8; 5; 9;4]

y=

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

>>x (1:3)

ans =

34 5

To find a particular value of x form first row and forth column in Matlab

>>x(1,4)

ans =

13
Produces a column vector, we have,

>>x(:)

ans =

Produces a row vector, we have,

>>x(1:end)

ans =

3 4 5 6 7

Entering a matrix (Two dimensional array ):

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,].

>> A=[42 5;7 7 9;2 2 3]

A=

42 5

7 7 9

2 2 3

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

>>A(3,2)

ans =

14
Matrix indexing:

In matrix A for example, A (1, 2) is an element of first row and second


column. Here A (1, 2) = 5.

Now, correcting any entry is easy through indexing. Here we substitute


A(3,2)=2 by A(2,2)=8 then

>>A(3,2)=0

A=

42 5

7 7 9

2 0 3

Transposing a matrix:

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

A=

4 2 5

7 7 9

2 2 3

>> A'

ans =

4 7 2

27 2

5 9 3

Creating a sub-matrix:

>> A=[42 5;7 7 9;2 2 3]

A=

15
4 2 5

7 7 9

2 2 3

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


the matrix A, then

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

B=

7 7

2 2

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

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

C=

2 2 3

7 7 9

42 5

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

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

ans =

Colon operator:

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

>> 1:13

16
ans =

1 2 3 4 5 6 7 8 9 10 11 12 13

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)

For example, we want to construct vector of say 6 elements


between 0 and 8.

>>linspace(0,6,10)

ans = 0 0.6667 1.3333 2.0000 2.6667 3.3333 4.0000


4.6667 5.3333 6.0000

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

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

ans =

0 0.1611 0.3222 0.4833 0.6444 0.8055 0.9666 1.1278


1.2889 1.4500 1.6111 1.7722 1.9333 2.0944 2.2555 2.4166
2.5777 2.7388 2.8999 3.0610 3.2221 3.3833 3.5444 3.7055
3.8666 4.0277 4.1888 4.3499 4.5110 4.6721 4.8332 4.9943
5.1554 5.3165 5.4776 5.6388 5.7999 5.9610 6.1221 6.2832

Colon operator in a matrix:

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

A=

3 5 7

2 7 7

17
2 9 4

For example,

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

ans =

2 9 4

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

>>A(:,1:3)

ans =

3 5 7

2 7 7

2 9 4

Deleting row or column:

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

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

A=

3 5 7

2 7 7

2 9 4

For example, second row of matrix A is deleted.

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

A=

3 5 7

2 9 4

Now to restore the deleted row :

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

A=

3 5 7

2 7 7

2 9 4

Dimension:

To determine the dimension of a matrix or vector, use the command size.

For example,

>>size(A)

ans =

3 3

Concatenating matrices:

The new matrix B

>> B=[A 10*A; -A [1 0 0;0 1 0; 0 0 1]]

B=

3 5 7 30 50 70

7 7 9 70 70 90

2 2 3 20 20 30

-3 -5 -7 1 0 0

-7 -7 -9 0 1 0

-2 -2 -3 0 0 1

Matrix generators:

19
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

Elementary matrice:

1.>> A=eye (3)

A=

1 0 0

0 1 0

0 0 1

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

B=

0 0 0 0 0

0 0 0 0 0

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

A=

1 1 1

1 1 1

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

A=

0.8147 0.9134

0.9058 0.6324

20
5.>> s=[1 2 4];

>>diag(s)

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.

>> x=zeros(5,5)

x=

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

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

x=

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

>>x(:,3:4)=ones(6,2)

x=

0 0 1 1 0

21
0 0 1 1 0

1 1 1 1 1

1 1 1 1 1

0 0 1 1 0

22
CHAPTER-3
Array Operations and Linear Equations

Array operations:

MATLAB has two different types of arithmetic operations: matrix arithmetic


operations and array arithmetic operations.

Matrix arithmetic operations:

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


matrices.

Using in MATLAB

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

A=

1 4 5

7 2 1

3 8 7

>> B=[2 2 6;8 5 2;4 6 2]

B=

2 2 6

8 5 2

4 6 2

>>A+B

23
ans =

3 6 11

15 7 3

7 14 9

>> A*B

ans =

54 52 24

34 30 48

98 88 48

>> A^2

ans =

44 52 44

24 40 44

80 84 72

>> A-B

ans =

-1 2 -1

-1 -3 -1

-1 2 5

>> A/B

ans =

0.7162 -0.4595 0.8108

-0.0135 1.2162 -0.6757

24
0.8514 -0.6216 1.5676

Array arithmetic operations:

Array arithmetic operations or array operations for short, are done by


element-by-element.

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

A=

5 2 3

7 5 6

7 2 9

>> B=[10 20 30;40 50 60;70 80 90]

B=

10 20 30

40 50 60

70 80 90

>> c=A.*B

c=

50 40 90

280 250 360

490 160 810

>> A.^2

ans =

25
25 4 9

49 25 36

49 4 81

Matrix and Array Operation:

Operation Matrix
Array
Addition +
+
Subtraction -
-
Multiplication *
.*
Division /
./
Left Division \ .\
Exponentiations ^
.^

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

4x +2y +6z = 8

2x +8y +2z = 4

6x +10y +3z = 0

This equation can be solved for x using linear algebra.

The result is x=inv(A)*b

Now there are two ways to solve x in MATLAB:

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

>> P =[4 3 6;22 2;6 8 3]

P=

4 3 6

2 2 2

6 8 3

>> q=[8;4;0]

q=

>> x=inv(P)*q

x=

38.0000

-24.0000

-12.0000

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

To solving system of linear equations by using well-known process


of Gaussian elimination

>> P=[4 3 6;2 2 2;6 8 3]

>> q=[8;4;0]

>> x=P\q

x=

27
38.0000

-24.0000

-12.0000

Matrix inverse:

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

A=

7 8 0

4 5 6

1 3 3

>>inv(A)

ans =

0.0435 0.3478 -0.6957

0.0870 -0.3043 0.6087

-0.1014 0.1884 -0.0435

Determinant of A is

>>det(A)

ans =

-69

Matrix functions:

Using MATLAB, determine the following:

(a) A+B

(b) AB

(c) A2

28
(d) AT

(e) B-1

(f) ATBT

(g)A2 +B2 AB

(h) determinant of A, determinant of B and determinant of AB

Solution:-

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

A=

3 5 1

2 5 4

8 8 7

>> B=[7 3 4;2 5 6;-3 3 7]

B=

7 3 4

2 5 6

-3 3 7

>> A+B

ans =

10 8 5

4 10 10

5 11 14

>> A*B

29
ans =

28 37 49

12 43 66

51 85 129

>> A^2

ans =

27 48 30

48 67 50

96 136 89

>> A'

ans =

3 2 8

5 5 8

1 4 7

>>inv(B)

ans =

0.1589 -0.0841 -0.0187

-0.2991 0.5701 -0.3178

0.1963 -0.2804 0.2710

>> A'*B'

ans =

59 64 53

82 83 56

30
47 64 58

>> A^2+B^2-A*B

ans =

42 59 55

42 73 64

9 78 15

>>det(A)

ans =

75

>>det(B)

ans =

107

>>det(A*B)

ans =

8.0250e+03

Example: Determine the Eigenvalues and eigenvectors of A and B

Solution:

% Determine the Eigenvalues and Eigenvectors

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

A=

4 5 -3

31
-1 2 3

2 3 7

>>eig(A)

ans =

2.3714 + 2.6858i

2.3714 - 2.6858i

8.2571

>> v=eig(A)

v=

2.3714 + 2.6858i

2.3714 - 2.6858i

8.2571

>> [v,d]=eig(A)

v=

0.8636 0.8636 -0.1061

-0.3053 + 0.3240i -0.3053 - 0.3240i 0.4436

-0.0400 - 0.2332i -0.0400 + 0.2332i 0.8899

d=

2.3714 + 2.6858i 0 0

0 2.3714 - 2.6858i 0

0 0 8.2571

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

B=

1 2 3

32
8 7 6

5 3 1

>>eig(B)

ans =

11.8655

-2.8655

0.0000

>>h=eig(B)

h=

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

33
34
CHAPTER-4
Introduction To Programming in MATLAB

Introduction:

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 different way of executing
repeatedly commands with MATLAB is:

1. To create a file with a list of commands

2. Save the file

3. Run the file.

M-File Scripts:

For example,

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 file: File New M-file.

Enter the following statements in the scriptfile:

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

b=[1;1;2] x=A\b Now Save the file. for example, example1.m. Run and
change folder, in the command line, by typing:

A=

1 2 3

35
3 3 4

2 3 3

b=

x=

-0.5000

1.5000

-0.5000

Example

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


= 0.5*cos(x), in the interval 0 x 2. Here we put the commands
in a file.

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);

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')

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

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

M-File functions:

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

Anatomy of a M-File function:

function f = factorial(n)

% FACTORIAL(N) returns the factorial of N.

% Compute a factorial value.

f = prod(1:n);

37
As an example, for n = 12, the result is,

>>factorial(12)

ans =

479001600

Anatomy of M-file function:

Part M-File Function Description


no.
1 Function definition line Define the function name, and the
number and the order of input and
output argument.
2 H1 line A one line summary description of the
program, displayed when you request
help.
3 Help text A more detailed description of the
program.
4 Function body Program code that performs the actual
computation.

Difference between scripts and functions:

Script Functions
Do not accept input arguments Can accept input arguments
or return output arguments. and return output arguments.
Store variables in a workspace Store variables in work space
that is shared with other internal to the function.
scripts. Are useful for extending the
Are useful for automating a Matlab language for your
series of commands. application.

Input and output arguments:

The input arguments are listed inside parentheses following the function
name. The output arguments are listed inside the brackets on the left side.

38
They are used to transfer the output from the function file. The general form
looks like this:

function [outputs] = function_name(inputs)

Function file can have none, one, or several output arguments.

Example of input and output arguments:

function C=FtoC(F) One input


argument
and
one output argument
function area=TrapArea(a, b, h) Three inputs
and one output
function [h, d]=motion(v, angle) Two inputs
and two outputs

Input to a script file

When a script file is executed, the variables that are used in the calculations
within the file must have assigned values. The assignment of a value to a
variable can be done in three ways.

1. The variable is defined in the script file.

2. The variable is defined in the command prompt.

3. The variable is entered when the script is executed.

We have already seen the two first cases. Here, we will focus our attention
on the third one. In this case, the variable is defined in the script file. When
the file is executed, the user is prompted to assign a value to the variable in
the command prompt. This is done by using the input command. Here is an
example.

gameA = input(Enter the points scored in the first game: );

gameB = input(Enter the points scored in the second game: );

gameC = input(Enter the points scored in the third game: );

Average = (gameA+gameB+gameC)/3

39
Now in Matlab:

>> Enter the points scored in the first game: 8

>> Enter the points scored in the second game: 9

>> Enter the points scored in the third game: 6

>>average = 7.66667

Output commands:

As discussed before, 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 Difference between these two commands can be summarized as
follows:

Disp . Simple to use.


. Provide limited control over the appearance of output

fprintf . Slightly more complicated than disp.


. Provide total control over the appearance of output

40
Chapter 5
Control flow and operators
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-files and function M-files. By creating a
file 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-files. MATLAB provides several tools that can be used to
control the ow of a program (script or function).

Control flow

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

The if...end structure

MATLAB supports the variants of if construct.

if ... end

if ... else ... end

if ... elseif ... else ... end

The simplest form of the if statement is:

if expression

statements

end

Here are some examples based on the familiar quadratic formula.

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

41
ifdiscr< 0
disp(Warning: discriminant is negative, roots are imaginary);
end
2. discr = b*b - 4*a*c;
ifdiscr< 0
disp(Warning: discriminant is negative, roots are imaginary);
elsedisp(Roots are real, but may be repeated)
end
3. discr = b*b - 4*a*c;
ifdiscr< 0
disp(Warning: discriminant is negative, roots are imaginary);
elseifdiscr == 0
disp(Discriminant is zero, roots are repeated)
elsedisp(Roots are real)
end

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

indentation of if block is not required, but facilitate the reading.

the end statement is required

Relational and logical operators:

Operator Description

42
> 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

The for...end loop

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

for variable = expression

statements

end

Usually, expression is a vector of the form I : a :b. A simple example of for


loop is

for h=1:7

h*h

end

Now in Matlab:

43
4

16

25

36

49

The while...end loop

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

while expression

statements

end

The statements are executed as long as expression is true.

s=1

while s <= 10

s = 5*s

end

now in command window:

>>s =

s=

s=

44
25

It is important to note that if the condition inside the looping is not well
defined, the looping will continue indefinitely. If this happens, we can stop
the execution by pressing Ctrl-C.

Other ow structures:

The break statement. A while loop can be terminated with the break
statement, which passes control to the first 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.

Operator precedence:

We can build expressions that use any combination of arithmetic, relational,


and logical operators. Precedence rules determine the order in which
MATLAB evaluates an expression.

Precedence Operator
1 Parentheses ()
2 Transpose (.0), power (. ), matrix power ( )
3 Unary plus (+), unary minus (), logical negation ()
4 Multiplication (.), right division (. /), left division (.\), matrix
multiplication (),
matrix right division (/), matrix left division (\)
5 Addition (+), subtraction ()
6 Colon operator (:)
7 Less than (<), less than or equal to (), greater (>), greater than or
equal to (),
equal to (==), not equal to (=)
8 Element-wise AND, (&)
9 Element-wise OR, (|)

Saving output to a file:

45
In addition to displaying output on the screen, the command fprintf can be
used for writing the output to a file. To save the results of some computation
to a file in a text format requires the following steps:

1. Open a file using fopen

2. Write the output using fprintf

3. Close the file using fclose

Example:

% write some variable length strings to a file

op = fopen(weekdays.txt,wt);

fprintf(op,Sunday\nMonday\nTuesday\nWednesday\n);
fprintf(op,Thursday\nFriday\nSaturday\n);

fclose(op);

ans=

Assignment-1
Part -1
Q.1

46
4
3+
5
a) Compute , 2 + 3 in command window.
5+
4

Ans:->> 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

Ans:- 1) Character string.


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


( 3 ).

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

ans =

32.0000 4.0000 81.0000 12.1825 63.0000 0.5000

d) Determine how long it takes light to travel to earth from a star 1


8
million miles away. The speed of light is 3* 10 m/s. Calculate the
problem in command window using Matlab.

Ans:->> r=1609344000;

>> s=3*10^8;

>> t = r/s

47
t=

5.3645

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

Ans:->> T=[7 4 3 4;2 6 3 8;9 10 11 12]

T=

7 4 3 4

2 6 3 8

9 10 11 12

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

S=

5 6 7 8

9 1 4 6

6 5 4 2

>> T+S

ans =

12 10 10 12

11 7 7 14

15 15 15 14

Part-2
6 43 2 11 87
Q.2 Create the following matrix A = 12 6 34 0 5 . Use the
34 18 7 41 9

matrix A to:

48
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.

Ans:->> 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(4,:)
vb =
11 0 41
c) >>vc=[A(1,:) A(2,:)]

vc =

6 43 2 11 87 12 6 34 0 5

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

vd =

43 6 18 87 5 9

Q.3 A trigonometric identity is given by

x tan x +sin x
cos2 2 = 2 tan x

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


x= 5

Ans:->> x=pi/5;

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

LHS =

0.9045

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

RHS =

0.9045

Part-3

Q.4

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)

Ans:->> g=9.81;

>>mass=[2 4 5 10 20 50]

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

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

Ans:->> 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

51
Assignment-2

Part-1
Question1. Start Matlab.

Solution:- After logging into account, we can enter MATLAB by double


clicking on the MATLAB shortcut icon on our windows desktop. When we start
MATLAB, a special window called the MATLAB desktop appears. The desktop
is a window that contains other windows. The major tools with or accessible
from the desktop are:

Command Window

Workspace

52
Command history

Current Directory

Help Browser

Start Button

Question2.Enter the following:

>> 1+2

Ans =

>> x=1+2

x=

>> x=1+2;

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

y=

23

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

53
>>pi

Ans=

3.141592653589793e+00

>>pi

Ans = 3.141592653589793e+00

>>format short e

>>pi

Ans =

3.1416e+00

>>format short

>>pi

Ans =

3.1416

Question4. Enter the following

= /

()^ + ()^

(() + ())

Solution:-

>> = /6

= 0.5236

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

Ans = 1

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

54
Ans = 72.0000

Question5. Enter the following :

a = [1 2 3]

b = [4 56]

c =a + ib

here is the square root of -1. You can use instead if that is what you are
use to.

Solution:-

>> = [1 2 3]

=1 2 3

>> = [4 5 6]

b= 4 5 6

>>c = +

c = 1.0000 + 4.0000 2.0000 + 5.0000 3.0000 + 6.0000

Question6.Display the real and imaginary parts of Z and the


conjugate of Z.

>>imag(z)

ans=

4 5 6

>>conj(z)

ans=

1.0000 - 4.0000i 2.0000 - 5.0000i 3.0000 - 6.0000

Question7. Display the magnitude and angle of Z.

Solution:-

>>mag = sqrt(y.^2+x.^2)

55
mag =

4.1231 5.3852 6.7082

>> a=angle(z)

a=

1.3258 1.1903 1.1071

Question8. Try the following

Z.

Solution:-

>>z'

ans =

1.0000 - 4.0000i

2.0000 - 5.0000i

3.0000 - 6.0000i

>>z.'

ans=

1.0000 + 4.0000i

2.0000 + 5.0000i

3.0000 + 6.0000i

Question9. Enter the two matrices

2 2 5 6
A= 3 4 B= 4 8

Solution: -

>> A= [2 2; 3 4]

56
A=

2 2

3 4

>> B=[5 6;4 8]

B=

5 6

4 8

Question10. Try the following and ensure you can follow what is happening:

>> A+5

7 7
Ans= 8 9

>> A+B

7 8
Ans = 7 12

>> A-B

3 4
Ans = 1 4

>> A*B

57
18 28
Ans = 31 50

>> A^2

10 12
Ans = 18 22

>> A'

2 3
Ans = 2 4

Question11. Solve the simultaneous equation on page 15 of the notes. A


should already be present from exercise 10.

= [ 5 ; 11] , = \ . Now check that x is the correct solution.

Solution:-

>> b=[5;11]

b=

11

>> x=A\b

x=

58
>> A*x

Ans =

Question12. It is just easy to solve a hundred simultaneous equations in a


hundred variables. First create a 100 by 100 matrix of random numbers. 1
= (100); If you forget to put in the semicolon, 10,000 numbers will be
printed out. Next create a column vector with 100 numbers . = (1:100)
.Now solve

=1\ .Check that the solution is correct. 1

Solution:-

>> A1= rand(100);

>> b= (1:100)'

b=

1 13 25 37 49 61 73 85 97

2 14 26 38 50 62 74 86 98

3 15 27 39 51 63 75 87 99

4 16 28 40 52 64 76 88 100

5 17 29 41 53 65 77 89

6 18 30 42 54 66 78 90

7 19 31 43 55 67 79 91

8 20 32 44 56 68 80 92

9 21 33 45 57 69 81 93

10 22 34 46 58 70 82 94

11 23 35 47 59 71 83 95

12 24 36 48 60 72 84 96

59
>> x=A1\b

x=

224.58 -281.28 -4.404 311.03 60.131 -85.583


81 87 8 98 6 6

49.454 163.13 -522.88 18.479 -46.425 -82.095


3 77 42 6 2 5

-80.065 172.76 118.47 71.726 -9.284 110.88


7 48 81 1 2 46

-146.23 -194.29 -141.59 -156.32 -7.445 -77.892


51 33 13 69 3 0

-83.740 -95.681 -216.20 20.920 78.871 103.73


0 5 97 2 8 20

52.338 231.01 187.55 72.842 9.054 -60.567


0 99 61 0 9 8

46.512 -82.682 -330.02 96.084 153.79 -78.677


4 5 71 7 69 5

-402.06 36.876 -122.40 109.33 60.373 21.439


00 1 00 19 3 0

105.38 -391.48 -409.94 -228.37 -89.210 174.28


44 97 42 31 0 99

181.19 220.38 212.21 163.14 -186.37 -262.98


17 16 82 72 26 18

331.66 0.881 323.32 33.955 -212.94 -261.48


81 4 39 3 02 11

-46.474 171.07 69.343 364.99 58.787 97.949


3 11 6 09 0 0

272.88 -4.303 -28.321 -49.175 -113.25 -177.73


19 0 5 6 25 53

60
-417.53 325.65 92.042 42.583 58.938 261.85
94 27 6 2 4 66

118.83 -147.48 283.19 -56.704 -109.84 171.04


25 41 50 6 55 64

-75.605 137.04 38.692 -129.14 -54.719


9 19 6 11 0

-110.04 -75.727 162.06 135.69 -67.767


96 9 36 51 2

>> A1*x

Ans=

1.00 10.00 19.00 28.00 37.00 46.00


00 00 00 00 00 00

2.00 11.00 20.00 29.00 38.00 47.00


00 00 00 00 00 00

3.00 12.00 21.00 30.00 39.00 48.00


00 00 00 00 00 00

4.00 13.00 22.00 31.00 40.00 49.00


00 00 00 00 00 00

5.00 14.00 23.00 32.00 41.00 50.00


00 00 00 00 00 00

6.00 15.00 24.00 33.00 42.00 51.00


00 00 00 00 00 00

7.00 16.00 25.00 34.00 43.00 52.00


00 00 00 00 00 00

8.00 17.00 26.00 35.00 44.00 53.00


00 00 00 00 00 00

9.00 18.00 27.00 36.00 45.00 54.00


00 00 00 00 00 00

61
55.00 71.00 79.00 87.00 94.00
00 00 00 00 00
63.000
56.00 0 72.00 80.00 88.00 95.00
00 00 00 00 00
64.00
57.00 00 73.00 81.00 89.00 96.00
00 00 00 00 00
65.00
58.00 00 74.00 82.00 90.00 97.00
00 00 00 00 00
66.00
59.00 00 75.00 83.00 91.00 98.00
00 00 00 00 00
67.00
60.00 00 76.00 84.00 99.00
00 00 00 00
68.00 92.000
61.00 00 0
00
69.00 77.000 85.000 100.00
62.00 00 0 0 0
93.000
00
70.00 78.00 86.00 0
00 00 00

62
Part-2

Question1. Enter the following :

>> A= [2 2;3 4]

A=

2 2

3 4

>> B= [5 6; 4 8]

B=

5 6

4 8

Question2. Now try the following array operations:

>> A.*B

Ans =

10 12

12 32

>> A.\B

Ans =

2.5000 3.0000

1.3333 2.0000

>> A.^B

Ans =

32 64

81 65536
>>sin(A*pi/6)

Ans =

0.9511 0.9511

0.9511 0.5878

>> A.^2

ans =

4 4

9 16

>>sqrt(D)

Ans =

2 2

3 4

>>clear

use clear to clear the workspace of all variables.

Question3. Plot the polynomial 2x3 x

x = linspace(1,1,100); y = 2x.^3 x;

What happens if you dont include the dot? plot(x,y)

Solution:-

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

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

>>plot(x,y)
Question4. Plot the polynomial 4x3 3x using the function polyval. First find
out how to use polyval using the help. doc polyval

p = [ 40 30]

y1 =polyval(p,x);

hold on

plot(x,y1,g)

Solution:-

>>doc polyval

>> p=[4 0 -3 0]

p=

4 0 -3 0

>> y1= polyval(p,x);

>> hold on
>>plot(x,y1,'g')
Question5. 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

Polynomial roots

Syntax : = ()

Description: = () returns a column vector whose elements are the


roots of the polynomial c. Row vector c contains the coefficients of a
polynomial, ordered in descending powers. If has + 1 component, the
polynomial it represents is 1 + + + +1.

Question6. Plot the roots of the polynomial onto the graph. ry =zeros(3,1)

The plot should still be held from exercise 4. plot(r,ry,rx) . Clear the
figure :clf

Solution:-

>> = ()

r=

0.8660

-0.8660

>>ry= zeros(3,1)

ry =

>> plot(r,ry,'rx')
Question7. Enter the following:

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

Question8. Enter the following :w = (1:5) (5:10)

This produces a 5 by 6 matrix. Set the third element on the second row of w
to 100.

Solution:-

>> 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

(2,3)=10

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
Question 9. Enter the following:

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

Ans =

12 14 16

18 21 24

24 28 32

>>w(2,:)

Ans =

10 12 14 16 18 20

>>w(:,5)

Ans =

18

27

36

45

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

Ans =

6 8

30 40
>>w(:)

Ans =

10

15 50

20 18

25 24 35

6 30 8

12 7 16 18

40 14 24 27

21 32 36

28 40 45

9 10

20

>>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

Question10. By now you should have a nice collection of variables. Try

who
whos

You will be able to see your variables in 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:

aans p r ry w x y y1

>>whos

Name Size Bytes Class Attributes

a 1x5 40 double

ans 30x1 240 double

p 1x4 32 double

r 3x1 24 double

ry 3x1 24 double

w 5x6 240 double

x 1x100 800 double

y 1x100 800 double

y1 1x100 800 double

>>clear
Clear command clear all the variables from workspace.

Q uestion11. Produce and a script called graph.

edit graph

In graph enter :x = linspace(2pi,2pi,100); y = sin(x); plot(x,y)

grid

Save by clicking on the icon and run by entering graph

In the command window.

Solution:-

>> edit graph

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

>> y=sin(x);

>>plot(x,y)

>>grid
Q. 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)
grid
holdon
y1=sin(x);
plot(x,y1,'r:d');
axis([-2*pi,-2,2])

Q.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))
Q.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))
Q.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))
xlabel ('degrees')

ylabel ('value')

grid

Q.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')

Q.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

Q.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')

grid

ylabel('value')
Practical Assignment
Q. 1: Find a short MATLAB expression to built the matrix

1 2 3 4 5 6 7
b= 9 7 5 3 1 1 3
4 8 16 32 64 128 256

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

Q.2. 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.

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

Q.3. Give a MATLAB expression that multiplies two vectors to


obtain a) the matrix

1 2 34 5
1 2 34 5
1 2 34 5

Solution:

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

ans =

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

b) matrix

Solution:

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

ans =

0 0 0

1 1 1

2 2 2

3 3 3
4 4 4

Q.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 2

Assignment-3

Q.1 Write a user defined Matlab function, with two input or two output
arguments that determines the height in cm. and mass in Kg of a person
from his height in inches and weight in pounds. For the function name and
arguments use [cm, kg] = value (in,lb).The input arguments are the height
in inches and weight in pounds, and the output arguments are the height
in cm. and mass in Kg. use the function in the command window to:

a) Determine in SI units the height and mass of a 5ft. 10 in. person who
weights 175 lb.
b) Determine your own height and weight in SI unit.

Sol. function [cm,kg] = value(in,lb)

cm = in*2.54
kg = lb*0.454

a) >>value(70,173)

cm =

177.8000

kg =

78.5420

ans =

177.8000

b)>>value(58,128)

cm =

147.3200

kg =

58.1120

ans =

147.3200

Q.2 Write a user defined Matlab function for the following math function:

r= 0.9a4-12a2-5a

The input to the function is x and output is r. Write the function such
that x can be a vector.

I. Use the function to calculate r(-7), and r(17).


II. Use the function to make a plot of the function s for -3a3
Sol. function [r] = opt(a)

r = (0.9*a.^4-12*a.^2-5*a);
plot(a, r);

I.
>>opt(-7)

ans =

1.6079e+03
>>opt(17)

ans =

7.1616e+04

II. >> x=[-3:0.1:3];

>>opt(x)

10

-10

-20

-30

-40

-50

-60
-3 -2 -1 0 1 2 3

Q.3 Write a user defined Matlab function for the following function:
r()= 2(1.1-sin2()). The input to the function (in radians) and the
output is r. write the function such that can be a vector:

1) Use the function to calculate r(/5) , and r(2/4)


2) Use the function to plot(polar plot)r() for 02

Sol. function [a] = eqt(theta)


a = 2*(1.1-sin(theta).^2)
polar(theta, a)

1) >> equation(pi/5)

a=

1.5090

ans =

1.5090

>>equation(2*pi/4)

a=
0.2000
ans =
0.2000

2) equation(0:0.08:2*pi)
90
2.5
120 60
2

1.5
150 30
1

0.5

180 0

210 330

240 300
270

Q.4 Write a user defined Matlab function that calculates the local
maximum or minimum of a quadratic function of the form:

f(x) = px2 + qx + r. for the function name and the arguments use [c, d] =
maxmin(p, q, r). The input arguments are the constants p, q and r, 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:

I. F(x)= 4x2-7x+22
II. F(x)=5x2-7x+2

Sol. [c, d] = maximin(p, q, r)


c= q/(2 function*p)
d= p*x^2+q*x + r
I.

>>>>maximin(4,7,22)

c=

0.7000

d=

42.3500

ans =

0.7000

>>maximin(5,-7,2)

c=

-0.7000

d=

9.3500

ans = -0.7000

Q.5 The value P of a savings account with an initial investment of P 0, and


annual interest rate r (in %), after t years is: P = P 0(1+r/100)t . Write the
user defined Matlabfunction that calculate the value of a savings account.
For the function name and arguments use P= mats(P 0, r, t). The input to
the 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 $10000 investment at an annual interest rate of 7% after
30years.

Sol. function[ p ] = loan( l, r, t )


p = l*(1+r/100)^t

>>loan(10000,7,30)

p=

7.6123e+04

ans =

7.6123e+04
Q.6 Write a user defined Matlab function that determines the angles of a
triangles when the lens of the size are given. For the function name and
the argument use [al, bet, gam] = triangle(a, b, c). Use the function to
determine the angles in 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

Sol. function [ al, bet, gam ] = tri( p, q, r )

r = acosd(p.^2+q.^2-r.^2)./(2*p*q)
p = acosd(q.^2+r.^2-p.^2)./(2*q*r)
q = acosd(r.^2+p.^2-q.^2)./(2*r*p)

1) >> tri(9, 15,10)


r=
0 + 1.2777i
p=
8.4477
q=
-15.2302 - 8.3382i

2) >> tri(200,300,210)
r=
0 + 0.0058i
p=
191.0211
q=
-3.0177e+02 - 8.1863e+01i

3)>>tri(7,9,10)

r=

0 + 1.8617i

p=

6.9143

q=

-9.5579 - 6.9918i
Q.7 Evaluate the following expressions without using Matlab. Check the
answer with Matlab:

1. 5 <= 8-3
2. Y=7<3-1+6>2
3. Y=(7<3)-1+(6>2)
4. Y= 2*4+5==7+20/4

Sol. Without using Matlab:

1.) 5<=5 is true .


2.) Y = 7<3-1+6>2 = 0-1+1 = 0
[because 7<3 not true so equal to zero and 6>2 is true which is equal to 1]
3.) Y = (7<3)-1+(6>2) = 0-1+1 =0
4.) Y = 2*4+5==7+20/4 = 13==12 which is not true.

Now , in Matlab:

1.) >> 5<=8-3

ans = 1

2.) >> 7<8>2

ans =

0
3.) >> (7<3)-1+(6>2)

ans =
0

4.) >> 2*4+5==7+20/4


ans =
0

Q.8 Given: a=10, b=6. Evaluate the following expressions without using
Matlab. Check the answer with Matlab:

1) Y = a>=b
2) Y = a-b<=b/2
3) Y = a-(b<=b/2)

Sol. 1) without Matlab :

10>=6 which is true .

Within Matlab:
>> a=10;

>> b=6;

>> a>=b

ans =

2)withoutMatlab:

4<=3 which is not true.

Within Matlab:

>>a-b<=b/2

ans =

3) without Matlab:
10-(6<=3) = 10
[because 6<3 is false i.e.= 0 ]

Within Matlab:

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

ans =

10

Q.9 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:

1) V>=w
2) W~=v

Sol. >> v= [4 -2 -1 5 0 1 -3 8 2];

>> w= [0 2 1 -1 0 -2 4 3 2];

1) without Matlab:
v=[4 5 0 1 8 2]
Within Matlab:

>> v>=w

ans =

1 0 0 1 1 1 0 1 1

>>withoutMatlab:

W=[0 2 1 -1 -2 4 3]

Within Matlab:

>> W~=v

ans =

1 1 1 1 0 1 1 1 0

Q.10 Use the vector v = [4 -2 -1 5 0 1 -3 8 2] and w = [0 2 1 -1 0 -2 4 3 2].


Use relational operators to create a vector y that is made up from the
elements of w that are greater than the elements of v.

Sol. .>> v= [4 -2 -1 5 0 1 -3 8 2];

>> w=[0 2 1 -1 0 -2 4 3 2];

>>Y=w>v

ans =

0 1 1 0 0 0 1 0 0

Q.11 Evaluate the following expressions without using Matlab. Check the
answer with Matlab:

1. 5& -2
2. 8-2|6+5& -2
3. ~(4&0) + 8*~(4|0)

Sol.>> 5&-2

ans =

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

ans =

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

ans =

Q.12 The maximum daily temperature (in 0F) for New York city and
Anchorage, Alaska during the month of January, 2001 are given in the
vector below(data from the U.S. National Oceanic atmospheric
administration).

T = [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]

S = [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:

1. Calculate the average temperature for the month in each city.


2. How many days was the temperature below the average in each
city?
3. How many days, and which dates in the month, was the temperature
in Anchorage higher than the temperature in New York?
4. How many days, and which dates in the months, was the
temperature same in both cities?
5. How many days, and which dates in the months, was the
temperature same in both cities above freezing (above 32 0F)?

Sol. T=[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];
S=[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];
avgk = mean(T)
avgl = mean(S)
a = sum(T<avgk)
b = sum(S<avgl)
c = S>T;
d = sum(e)
e = find(e)
f = (T==S);
g = sum(o)
h = find(o)
i = sum((T>32)&(S>32))
j = find((T>32)&(S>32))

>>mine

avgl =
37.6774

avgl =
33.1290

a=
17

b=
13

c=
11

d=
1 7 9 14 15 18 19 21 22 25 26

e=
1

f=
23

g=
16

h=
7 8 9 13 14 15 16 17 18 19 20 23 24 25 26 27