Professional Documents
Culture Documents
Command window
Command history
Workspace
Current directory
Help browser
Start button
MATLAB was written originally to provide easy access to matrix software developed
by the LINPACK (linear system package) and EISPACK (Eigen system package)
projects.
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.
>> 4+6*9
ans =
58
- Subtraction 4-5
* Multiplication 2*10
/ Division 2/11
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
>> (8+7)*9
ans =
135
>> 8+7*9
ans =
71
By adding parentheses, these two expression give different results: 135 and 71.
3
1/4+ +6/7*3/5
In MATLAB, it becomes
ans =
0.5912
>> 1/4+3^2+6/7*3/5
ans =
9.7643
Then x= 9+7*8-5,
>> x= 9+7*8-5
x=
60
>> 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.
>> x=-234.5675
x=
-234.5675
>> x=-234.5675
x=
-2.345675000000000e+02
For example,
y=
-6.7997
z=
1.4905e+03
5
CHAPTER:-2
CREATING ARRAYS AND BASIC PLOTTING
Example:
1) The value of expression y = sin(y) +15x, for a = 12, x= 5, and y = 9 is
computed by
z=
33.5410
6
The subsequent examples are
v=
4.1744
v=
1.8129
>> 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
>> x= [1 4 5 6 9 12];
>> y= [4 -2 4 8 7 11];
>> plot(x,y)
>> xlabel('x--->')
>> ylabel('y--->')
8
2.2.2 Creating a Sine wave (one dimensional plot):-
To create a Sine wave in MATLAB command window.
>> y=sin(x);
>> plot(x,y,'g-')
>> xlabel('x-axis')
>> ylabel('y-axis')
>> 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
>> 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,'--')
>> 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
>> y1=2*cos(x);
>> y2=cos(x);
>> y3=0.5*cos(x);
>> plot(x,y1,'--',x,y2,'-',x,y3,':')
>> legend('2*cos(x)','cos(x)','0.5*cos(x)')
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.
>> u=[ 3 4 7 8 9]
u=
3 4 7 8 9
14
>> v= [2; 6;9;8;5]
v=
>> 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 =
>> u(:)
ans =
>> 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.
For example,
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
>> B(3,1)
ans =
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'
ans =
1 2 7
5 2 9
3 6 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=
17
5 6
8 5
C=
6 8 5
3 2 1
4 5 6
>> A(end:-1:1,end)
ans =
It is denoted by (:).
For example,
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> 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,
>> x= linspace(0,15,10)
x=
Columns 1 through 7
Columns 8 through 10
>> y=linspace(0,2*pi,40)
y=
Columns 1 through 3
0 0.161107315568707 0.322214631137415
Columns 4 through 6
Columns 7 through 9
Columns 10 through 12
Columns 13 through 15
19
1.933287786824488 2.094395102393196 2.255502417961903
Columns 16 through 18
Columns 19 through 21
Columns 22 through 24
Columns 25 through 27
Columns 28 through 30
Columns 31 through 33
Columns 34 through 36
Columns 37 through 39
Column 40
6.283185307179586
A matrix A=
A=
4 5 7
5 7 9
20
1 7 4
For example,
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
>> 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
1 9 4
Now to restore the deleted row , we use a technique for creating a matrix
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
A=
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
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
>> 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
A= B=
A=
2 4 5
8 9 10
3 6 9
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
81 120 156
>> A-B
ans =
-18 -36 -1
0 -1 8
-1 -3 8
>> A/B
ans =
27
Table 3.1.2: Array operations:
.* Element-by-element multiplication
./ Element-by-element division
.^ Element-by-element exponentiation
X= Y=
X=
2 4 5
9 6 10
11 9 8
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 =
A= and vector b =
This equation can be solved for x using linear algebra. The result is x= .
A=
2 4 3
4 3 6
1 2 3
b=
29
>> x=inv(A)*b
x=
-4.2000
0.6000
3.3333
>> x=A\b
x=
-4.2000
0.6000
3.3333
A=
= 1/9
A=
1 2 3
4 5 6
7 8 0
30
>> inv(A)
ans =
= 1/9
And determinant of A is
>> det(A)
ans =
27.0000
For example,
X = Y =
31
Using MATLAB, determine the following:
a) XY
b) X+Y
c)
d)
e)
f)
g)
h)
Solution:
X=
40 0 1
20 3 30
-1 10 7
Y=
10 7 8
3 5 6
1 2 0
a) >> X*Y
ans =
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
f) >> X'*Y'
ans =
532 214 80
101 75 6
276 195 61
g) >> inv(Y)
ans =
33
-0.0857 0.1143 0.5143
h) >> X^2+Y^2-2*X*Y
ans =
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:
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=
D=
0.5949 0 0
0 3.0000 0
0 0 8.4051
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=
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:
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
Example1,
x + 2y + 3z = 1
3x + 3y + 4z = 1
2x + 3y + 3z = 2
Solution:-
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,
Solution:
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,':')
ylabel('Cosine functions')
legend('2*cos(x),cos(x),0.5*cos(x)')
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
function f = factorial(n)
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
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
Table 4.4:
Scripts Functions
Do not accept input arguments or return Can accept input arguments or return
output arguments. output arguments.
- Are useful for automating a series of Are useful for extending the MATLAB
commands language for your application
>> 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
function[outputs] = function_name(inputs)
Function le can have none, one, or several output arguments. Some possible
combinations of input and output arguments.
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.
The command prompt when this script file saved as example9 is executed.
>> example9
Avg =
62.3333
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)
43
Example of disp command: The script file to calculate the average point scored
in three games.
Now save the file name game, run the file, in the command window.
>> game
avg =
7.6667
avg
Example of fprintf command: The script file to calculate the average point
scored in three games.
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:
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
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.
Solution:
%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.1. if statement:-
The simplest form of the if statement is
If expression
statements
end
1) if ..end
a=4; b=5;c=25;
discr=b*b-4*a*c;
if discr<0
disp('warning: discriminant is negative,root are imaginary');
end
47
>> discriminant
warning: discriminant is negative,root are imaginary
2) if else..end
Example:
a=45; b=50;
if(a>b)
else
disp('b is grater than a')
end
>> greater
b is grater than a
3) if..elseif.else.end
Example:
a=4; b=4;
if(a>b)
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
statements
end
for i=1:5;
x=i+3*i-34
end
>> ccc
x=
-30
x=
-26
x=
-22
x=
-18
x=
-14
while expression
statements
end
49
Example:
x=2
while x<=11
x=5*x
end
>> ddd
x=
x=
10
x=
50
Operator Description
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 =
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:
Run-time errors - Run-time errors are usually apparent and dicult to track down.
They produce unexpected results.
Setting breakpoints
Examining values
Correcting problems
Ending 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:
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.
K>>
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.
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.
Quit debugging.
Clear breakpoints.
54
ASSIGNMENT NO:-1
PART - 1
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
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
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
b = [4 5 6]
Z = a + i *b
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=
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 =
Solution:-
>>abs(Z)
ans =
>>angle(Z)
ans =
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
A= B=
Solution:-
>> A=[1 2;3 4]
A=
1 2
3 4
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
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
A1 = rand(100);
If you forget to put in the semicolon, 10,000 numbers will be printed out.
b = (1:100)
Now solve
x = A1/b
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=
62
325.7246 128.6720 99.5035 85.2169 -81.5710
>> A1*x
ans =
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=
Solution:-
>>A=[1 2;3 4]
A=
1 2
3 4
B=
5 6
7 8
A./B
A.^B
Sin(A*pi/6)
D=A.^2
Sqrt(D)
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
y = 2*x.^3-x;
Plot (x,y)
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.
ry = zeros(3,1)
68
Plot (r, ry,rx)
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=
>>a(2)
ans =
2.5000
>>a([2 4])
ans =
2.5000 3.5000
>>a(2:4)
ans =
>>a(2:end)
ans =
Solution:-
70
>>a(2)
ans =
2.5000
>>a([2 4])
ans =
2.5000 3.5000
>>a(2:4)
ans =
>>a(2:end)
ans =
>> 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.
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.
Solution:-
>>who
a a1 ans b b1 d g p q r ry w x y y1 z
>>whos
a 1x5 40 double
b 2x2 32 double
d 2x2 32 double
p 1x4 32 double
q 1x4 32 double
r 3x1 24 double
ry 3x1 24 double
75
w 5x6 240 double
In graph enter
x = linspace(-2*pi,2*pi,100);
y = sin(x);
plot(x,y)
grid
graph
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])
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)
% x = mysqrt(A)
while (err>0.0001)
end
78
function y=myfunction(A,x)
Y=(x.^2+A)./(2*x);
Test the function by enter the following into the command window.
mysqrt(9)
mysqrt(2)
help mysqrt
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;
>> 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))
Solution:-
>> degrees = 0:6:360;
>> 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.
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
Solution:-
degrees=0:6:360;
rad=degrees*pi/180;
plot(degrees,sin(rad))
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')
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')
title('tan wave')
xlabel('degrees')
ylabel('value')
grid
84
85
PRACTICAL ASSIGNMENT
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
Solution:-
>> b*[0 0 0 0 1 0 1]'
ans =
12
-2
320
Solution:-
>> [0 0 1]*b
ans =
4 8 16 32 64 128 256
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
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
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:-
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:
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:-
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
>> A+B
ans =
6 8 10 12
14 7 11 14
15 15 15 14
90
PART- 2
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
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
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 =
>> mv=force./(mass*g)
mv =
>> 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.
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).
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.
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.
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
P= ( )
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
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:
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
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+
=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
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
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]
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