Professional Documents
Culture Documents
SHIMLA HILLS
MATLAB PROGRAMMING
MATLAB 402
Introduction
Starting MATLAB
After logging into your account, you can enter MATLAB by double- clicking
on the MATLAB shortcut icon (MATLAB 7.0.4) on your Windows desktop.
When you start MATLAB, a special window called the MATLAB desktop
appears. The desktop is a window that contains other windows. The major
tools within or accessible from the desktop are:
The Command Window
The Workspace
>> X = 1+3*3
X=
10
+ Addition 2+3
- Subtraction 23
Multiplicatio
n 23
/ Division 2/3
Quitting MATLAB
To end your MATLAB session, type quit in the Command Window, or select
File/Exit MATLAB in the desktop main menu.
Creating MATLAB variables
For example,
>> x = expression
built-in functions
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 looks like this:
>> a = 7;
>> a = a+ 1
>> a =
8
Error messages
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
>> x = 10;
>> 5x
??? 5x
|
Error: Unexpected MATLAB expression.
>>2+2*3
ans =
8
For operators of equal precedence, evaluation is from left to right .
In Matlab
>> 1/(3+4^2)+5/6*7/8
ans =
0.7818
Or if parenthesis missing
>>1/3+4^2+5/6*7/8
ans=
17.0625
>> clear
The command clear or clear all removes all variable s from the workspace.
This frees up system memory. In order to display a list of the variable s
currently in the memory, type >> who while, whos will give more details which
include size, space allocation, and class of the variable s.
>> diary
>> x=9;
b=cos(x)
c=cosh(x)
b =cos(x) =
-0.9111
c = cosh(x) =
4.0515e+0.3
Chapter 2
There is a long list of mathematical functions that are built into MATLAB.
These functions are called built-ins. Many standard mathematical functions,
such as sin(x), cos(x), tan(x), ex, ln(x), are evaluated by the functions sin,
cos, tan, exp , and log respectively in MATLAB.
Table 2.1 lists some commonly used functions, where variables x and y
can be numbers, Vectors or matrices.
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
asin(x) Arc sine ceil(x) Round towards +1
atan(x) Arc tangent floor(x) Round towards -1
round(x Round to nearest
exp(x) Exponential ) integer
Remainder after
sqrt(x) Square root rem(x) division
Natural angle(x
log(x) logarithm ) Phase angle
Common
log10(x) logarithm conj(x) Complex conjugate
Examples
We illustrate here some typical examples which relate d to the elementary
functions previously denned.
y=
28.2904
>>log(142)
ans=
4.9558
>>log10(142)
ans=
2.1523
Note the difference between the natural logarithm log(x) and the decimal
logarithm (base 10) log10(x).
To calculate sin( = 4) and e 10, we enter the following commands in
MATLAB,
>>sin(pi/4)
ans =
0.7071
>>exp(10)
ans =
2.2026e+ 0013
Notes:
>>y = [ 3 2 -1 5 6 8] ;
>> plot(x,y)
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y)
MATLAB enable s you to add axis labels and title s. For example, using the
graph from the previous example, add an x- and y- axis labels.
Now label the axes and add a title . The character \pi creates the
symbol . An example of 2D plot.
>>ylabel('Sine of x')
The colour of a single curve is, by default, blue, but other colours are
possible. The desired colour is indicated by a third argument. For
example, red is selected by plot(x ,y ,'r'). Note the single quotes, ' ',
around r.
>> 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')
>> lege nd('2*cos(x)','cos(x)','0.5*cos(x)')
>> title ('Typical example of multiple plots')
>> axis([ 0 2*pi -3 3] )
Specifying line styles and colours
It is possible to specify line styles, colours, and markers (e.g., circles, plus
signs, . . . ) using the plot command:
plot(x,y,'style_colour_marker')
where style_colour_marker is a triplet of values from
Table 2.3 To find additional information, type help plot or doc plot
Entering a vector
1 2 7 9 13
Column vectors are created in a similar way, however, semicolon (;) must
separate the components of a column vector,
>> w=[1;2;7;9;13]
w=
1
2
7
9
13
On the other hand, a row vector is converted to a column vector using the transpose
operator. The transpose operation is denote d by an apostrophe
or a single quote (').
>> w = v
w=
1
2
7
9
13
Thus, v(1) is the first element of vector v, v(2) its second element, and so
forth. Furthermore, to access blocks of elements, we use MATLAB's
colon notation (:).
For example, to access the first three elements of v, we write,
>>v(1:3)
ans=
1 2 7
Or, all elements from the third through the last elements,
>> v(3,end)
ans=
7 9 13
where end signifies the last element in the vector. If v is
vector, writing
>> v(:)
produces a column vector,
whereas writing
>> v(1 :end)
produces a row vector.
Entering a matrix
A matrix is an array of numbers. To type a matrix into MATLAB
you must begin with a square bracket,
>> A= [ 3 2 1 ; 6 5 4; 9 8 7]
Note that the use of semicolons (;) here is different from their use mentioned
earlier to suppress output or to write multiple commands in a single line.
Once we have entered the matrix, it is automatically stored and remembered
in the Workspace. We can refer to it simply as matrix A. We can then view
a particular element in a matrix by specifying its location. We write,
>> A(2,1)
ans=
4
A(2,1) is an element located in the second row and first column. Its value is 4.
Matrix indexing
We select elements in a matrix just as we did for vectors, but now we
need two indices. The element of row i and column j of the matrix A is
denote d by A(I ,j) . Thus, A(i, j) in MATLAB refers to the element Aij of
matrix A. The first index is the row number and the second index is the
column number. For example, A(1,3) is an element of first row and third
column.
Here , A(1,3)=3.
Correcting any entry is easy through indexing. Here we
substitute A(3,3)=9 by A(3,3)=0.
The result is >>A(3,3) = 0
A=
3 2 1
6 5 4
0 8 7
Colon operator
The colon operator will prove very useful and understanding how it works
is the key to efficient and convenient usage of MATLAB. It occurs in
several different forms.
Often we must deal with matrices or vectors that are too large to enter one
element at a time. For example, suppose we want to enter a vector x
consisting of points (0; 0:1; 0:2; 0:3; .. 5). We can use the command
>> x =[ 0:0.1:5];
The row vector has 51 elements.
Linear spacing
On the other hand, there is a command to gene rate linearly spaced vectors:
linspace . It is similar to the colon operator (:), but give s direct control over
the number of points. For example,
y = linspace (a,b)
generates a row vector y of 100 points linearly spaced between and
including a and b.
y = linspace (a,b,n)
generates a row vector y of n points linearly spaced between and including
a and b. This is useful when we want to divide an interva l into a
number of subintervals of the same length . For example,
>> theta = linspace (0,2*pi,101)
divide s the interval [ 0; 2 ] into 100 equal subintervals, then creating a
vector of 101 elements.
6 5 4
>> A(:,2:3)
ans=
2 1
5 4
8 7
>> A(:,2)=[ ]
Ans =
3 1
6 4
0 7
Creating a submatrix
To extract a sub matrix B consisting of rows 2 and 3 and columns 1 and 2 of
the matrix A, do the following
>>B= A([ 2 3],[1 2] )
B=
6 5
0 8
To interchange rows 1 and 2 of A, use the vector of row indices together with
the colon operator.
>> C = A([2 1 3],:)
C=
6 5 4
3 2 1
0 8 7
It is important to note that the colon operator (:) stands for all columns or all
rows. To create a vector version of matrix A, do the following
>>A(:)
ans =
3
2
1
6
5
4
0
8
7
The sub matrix comprising the intersection of rows p to q and columns r to s
is denote d by A(p:q,r:s).
As a special case, a colon (:) as the row or column specified covers all
entries in that row or column; thus
A(:,j) is the jth column of A, while
A(i,:) is the ith row, and
A(end,:) picks out the last row of A.
Deleting row or column
To delete a row or column of a matrix, use the empty vector
operator, [ ]
.
>> A(3,:) = [ ]
A=
3 2 1
6 5 4
Third row of matrix is now dele ted. To restore the third row, we use a
technique for creating a matrix
>> A= [ A(1,:);A(2,:);[ 0 8 7] ]
A=
3 2 1
6 5 4
0 8 7
Dimension
To determine the dimensions of a matrix or vector, use the command size . For
example,
>> size(A)
ans=
3 3
ans=
25
Transposing a matrix
The transpose operation is denote d by an apostrophe or a single quote (').
A matrix about its main diagonal and it turns a row vector into a column
vector. Thus,
>> A
ans =
3 6 0
2 5 8
1 4 7
Concatenating matrices
Matrices can be made up of sub-matrices. Here is an example. First, let's recall our
previous matrix A.
A=
3 6 9
2 5 8
1 4 7
The new matrix B will be,
3 6 9 30 60 90
2 5 8 20 50 80
1 4 7 10 40 70
-3 -6 -9 1 0 0
-2 -5 -8 0 1 0
-1 -4 -7 0 0 1
Matrix generators
MATLAB provides functions that gene rates elementary matrices. The
matrix of zeroes, the matrix of ones, and the identity matrix are returned
by the functions zeroes , ones, and eye, respectively.,
Elementry matrix eye (m, n) returns an m by- n matrix with 1 or the main
diagonal eye (n) returns n- by-n square identity matrix zeroes (m, n) returns as n-
by- n matrix of zeroes ones (m, n) Returns an m -by-n matrix of ones diag(A)
Extracts the diagonal of matrix A rand(m, n) Returns an m -by-n matrix of random
numbers.
For a complete list of elementary matrices and matrix manipulations , type
help elmat or doc elmat . Here are some examples:
1. >> c=ones(3,1)
c=
1
1
1
2. >> eye(3)
ans =
1 0 0
0 1 0
0 0 1
3. >> c= zeroes(2,3)
c=
0 0 0
0 0 0
In addition, it is important to remember that the three elementary operations
of addition (+ ), subtraction (), and multiplication ( ) apply also to matrices
whenever the dimensions are com partible .
Two other important matrix gene ration functions are rand and rand , which
generate matrices of (pseudo)random numbers using the same syntax as
eye.
In addition, matrices can be constructed in a block form . With C denoted by
C = [ 1 2; 3 4] , we may create a matrix D as follows >> D = [ C zeros(2);
ones(2) eye(2)]
D=
1200
3400
1110
1101
Chapter 3
On the other hand, array arithmetic operations or array operations for short,
are done element-by-element . The period character, ., distinguishes the
array operations from the matrix operations. However, since the matrix
and array operations are the same for addition (+ ) and subtraction (), the
character pairs (:+ ) and (:) are not used. If A and B are two matrices of the
same size with elements
A= [ aij ] and B = [ bij ] , then the command 30
.* Element- by-element multiplication
./ Element- by-element division
.^ Element- by- element exponential array operator
>> A=[6 6 9 ;5 3 7 ;1 9 4]
>> B= 10 30 50
20 10 10
80 20 30
>> C= A.*B
>> C=
60 180 400
100 30 70
80 180 120
produces another matrix C of the same size with elements cij = aij bij . For
example, using the same 3 3 matrices A, we have
>>A.^2
ans =
36 36 81
25 9 49
1 81 36
B=
9 8 7
6 5 4
3 2 1
C=
1
1
1
Matrix inverse
Let's consider the same matrix B.
>> A=(inv) B C
>> A=
-2.0000
5.0000
-1.5000
>> A = (inv)B
A=
-0.4504 0.9007 -0.4504
0.9007 -1.8014 0.9007
-0.4504 0.9007 -0.4504
and the
determinant of B is
>> det(B)
ans =
0
Chapter 4
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 execute d again for several times. Therefore, a
different way of executing repeatedly commands with MATLAB is:
1. to create a file
2. save the file, and
3. run the file.
If needed, corrections or changes can be made to the commands in the file. The
files that are used for this purpose are called script files or scripts for short.
This section covers the following topics:
M-File Scripts
M-File Functions
M-File Scripts
Examples
3x + 3y + 4z = 1
2x + 3y + 3z = 2
>> example1
x =
-0.5000
1.5000
-0.5000
Or
>> edit filename.m
to open a file name
Example
Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0:5
cos(x), in the interval [0 x 2] .This example has been presented in
previous Chapter. Here we put the commands in a file.
Create a file, say example 2.m ,
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
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')
axis([0:2*pi,-3 :3])
Script side -effects
All variable s created in a script file are added to the workspace. This may
have undesirable effects, because:
Variables already existing in the workspace may be overwritten.
The execution of the script can be a effected by the state variable s in
the workspace. As a result, because scripts have some undesirable
side-effects, it is better to code any complicated applications using rather
function M-file.
In this case, the variable is defined in the script file. When the file is execute d,
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.
The following shows the command prompt when this script file is executed.
Example 3
>> Enter the points scored in the first game 20
>> Enter the points scored in the second game 50
>> Enter the points scored in the third game 35
Average = 35
input command can also be used to assign string to a variable .
Output commands
>> edit
Chapter 5
Control flow
MATLAB has four control flow structures: the if statement, the for loop, the while
loop, and the switch statement.
The ``if...end'' structure
if ... end
if ... else ... end
if expression statements
end
Operator Description
Note that the equal to" relational operator consists of two equal signs (==)
(with no space between them), since = is reserved for the assignment operator.
loop ``for...end''
In the for ... end loop, the execution of a command is repeated and
predetermined number of times. The syntax is
end
Usually, expression is a vector of the form i:s:j. A simple example of for loop is
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
It is important to note that if the condition inside the looping is not well denned,
the looping will continue indefinitely. If this happens, we can stop the execution
by pressing Ctrl-C.
Introduction
Debugging process
We can debug the M-files using the Editor/Debugger as well as using debugging
functions from the Command Window. The debugging process consists of
You cannot set breakpoints while MATLAB is busy, for example, running
an M-file.
After setting breakpoints, run the M-file from the Editor/Debugger or from the
Command Window. Running the M-file results in the following:
K>>
indicating that MATLAB is in debug mode.
The program pauses at the first 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.
Ending debugging
Quit debugging
Do not make changes to an M-file while MATLAB is in debug mode
Make changes to the M-file
Save the M-file
Clear breakpoints
Assignment -1
PART-1
Q 1. Start Matlab.
Ans:- 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:
The Command Window
The Command History
The Workspace
The Current Directory
The Help Browser
The Start Button
Q 2. Enter the following
1+2
x=1+2
x = 1 + 2;
y = x^2 + 2 + 8
Ans: - >> 1 + 2
ans = 3
>> x = 1 + 2
x=3
>> = 1 + 2;
>> = x^2 + 2 x + 8
y = 23
Ans: -
>>format long e
>> pi
ans = 3.141592653589793 + 00
>> format long
>> pi
ans = 3.141592653589793
>> format short e
>> pi
ans = 3.1416 + 00
>> format short
>> pi
ans = 3.1416
a = [ ]
b = [ ]
z = a+ i b
i here is the square root of -1. You can use j instead if that is what you are used.
Ans: >> a = [1 2 3]
a= 1 2 3
>> b = [4 5 6]
2.
3.
Q 9. Enter the two matrices
A= 1 2 ,B = 5 6
3 4 7 8
Ans:
Q 10. Try the following and ensure you can follow what is
happening.
A+5 , A+B ,A-B , A*B ,A^2 ,A ,B=[5;11]
Ans:-
1 3
2 4
If you forget to put in the semicolon, 10,000 numbers will be printed out.
Next create a column vector with 100 numbers
Now solve
check that the solution
is correct.
Ans:-
Part 2
A= 1 2 B= 5 6
3 4 7 8
Ans:
Ans:-
>>
Q 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?
Ans: - 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 components, the polynomial it represents is
.
Q 6. Plot the roots of the polynomial onto the graph.
Ans:
Q 7. Enter the following
Ans:-
Ans:-
Q10. 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.
Ans:-
Clear command clear all the variables from workspace.
Ans:-
Assignment 2
Q 1. Find a short MATLAB expression to build the matrix
1 2 3 4 5 6 7
B= 9 7 5 3 1 -1 -3
4 8 16 32 64 12 256
Ans:-
Ans- (i)
(ii)
(iii)
Q3. Give a MATLAB expression that multiplies two vectors to
obtain
1 2 3 4 5 0 0 0
(a) The matrix 1 2 3 4 5 , (b) the matrix 1 1 1
1 2 3 4 5 2 2 2
3 3 3
4 4 4
Ans: - (a)
(b)
(a) Create a 3X4 matrix B from the 1st, 3rd, and 4th rows, and the 1st, 3rd through
5th, and 7th columns of the matrix A.
(b) Create a 15 elements long row vector u from the elements of the third row,
and the 5th and 7th columns of the matrix A.
Ans: -
(b)
Assignment-3
Part -1
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.
c) Create a row vector that has the elements: 32, 4, 81, , 63, cos (pi/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 million
miles away.The speed of light is 3*108 m/s. Calculate the problem in
command window using Matlab.
Ans:->>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 byelement.
Ans:->> 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=
5678
9146
6542
>> A+B
ans =
6 8 10 12
14 7 11 14
15 15 15 14
Part-2
Q.2 Create the following matrix A =
6 43 2 11 87
12 6 34 0 5
34 18 7 41 9
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.
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
d) >>vd=[A(4:6) A(13:15)]
vd =
43 6 18 87 5 9
Q.3 A trigonometric identity is given by
Cos^2(x/2)=tan x+sin x/2tan x
Verify that the identity is correct by calculating each side of the equation,
substituting x = pi/5.
Ans:->>x=pi/5;
>>LHS=(cos(x/2))^2
LHS =
0.9045
>>RHS=(tan(x)+sin(x))/(2*tan(x))
RHS =
0.9045
LHS = RHS
Part-3
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
Practical Assignment - 3
Q.1 Find a short MATLAB expression to built the
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 use only a single matrix multiplication
with B to obtained
(a) The sum of columns 5 and 7 of B.
(b) The last row of B.
(c) A version of B with rows 2 and 3 swapped.
Ans:-(a)
B=
1 2 3 4 5 6 7
9 7 5 3 1 -1 -3
4 8 16 32 64 128 256
C=
0
0
0
0
1
0
1
>> D=B*C
D=
12
-2
320
(b)
B=
1 2 3 4 5 6 7
9 7 5 3 1 -1 -3
4 8 16 32 64 128 256
>> E=[0 0 1]
E=
0 0 1
>> F=E*B
F=
4 8 16 32 64 128 256
(c) >> G=[1 0 0;0 0 1;0 1 0]
G=
1 0 0
0 0 1
0 1 0
B=
1 2 3 4 5 6 7
9 7 5 3 1 -1 -3
4 8 16 32 64 128 256
>> H=G*B
H=
1 2 3 4 5 6 7
4 8 16 32 64 128 256
9 7 5 3 1 -1 -3
Ans:-
A=
1 2 3 4 5 6 7
11 12 12 13 14 5 6
9 10 16 18 19 20 21
22 23 24 25 26 27 28
>> X=[A(3,:),A(17:20),A(25:28)]
X=
9 10 16 18 19 20 21 5 14 19 26 7 6 21 28
Assignment 4
Q.1 Write a user- defined MATLAB function, with two input and two output
arguments that determines the height in centimetres 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 argument are the height in
centimetres and the mass in kilograms. Use the function in the Comand Window
to:
a) Determine in SI units the height and mass of a 5 ft.10 in. person who weights
175 lb.
Soln:
function[cm,kg]= STtoSI(in,lb)
cm =in*2.54;
kg =lb*.454;
end
>> STtoSI(70,175)
cm =177.8000
kg =79.4500
ans =177.8000
b) >> STtoSI(55,163)
cm =139.7000
kg =74.0020
ans =139.7000
Q.2 Write a user defined MATLAB function for the following math
function:
y(x) = 0.9x4-12x2-5x
The input to the function is x and the output is y. Write the function
such that x can be a vector.
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 -4x4.
Soln:
function[y]=equation(x)
y=0.9*x^4-12*x^2-5*x
end
>> equation(-3)
y =-20.1000
>> equation(5)
y = 237.5000
b) x=[-4:0.03:4];
y=0.9*x.^4-12*x.^2-5*x;
plot(x,y)
graph:-
Q.3 Write a user defined MATLAB function for the following function:
r() = 2(1.1-sin2)
The input to the function is (in radian) 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 02.
Sol.
function[r]=input(theta)
r =2*(1.1-(sin(theta))^2)
end
>> input(pi/3)
ans =
0.7000
>> input((3*pi)/2)
ans =
0.2000
b) theta=[0:0.03:2*pi]
r =2*(1.1-(sin(theta)).^2)
polar(r,theta)
Q.4 Write a user- defined MATLAB function that calculates the local
maximum or minimum of a quadratic of the form: f(x) = ax2+bx+c. For the function
name and argument 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 minimum.
Use the function to determine the maximum or the minimum of the following
functions:
a) 3x2-18x+48
b) -5x2+10x-3
Soln:
function[x,y] =maxmin(a,b,c)
x=-b/(2*a)
y=a*x^2+b*x+c
end
>> maxmin(3,-18,48)
ans =
3
>> maxmin(-5,10,-3)
ans =
1
Q.5 The value P of a savings account with an initial investment of P0 , and annual
interest rate (in %), after t years is:
P =P0(1+R/100)t
Write a user-defined MATLAB function that calculates the value of savings
account. For the function name and arguments use P =saval(P0,r,t). The inputs 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
$10,000 investment at an annual interest rate of 6% after years.
Sol.
function[P] = saval(P0,r,t)
P =P0*((1+(r/100))^t);
end
>> saval(10000,6,13)
P =2. 1329e+04
Q.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.
Sol.
function[Nm]=lbintoNm(lbin)
Nm =0.1129*lbin
end
>> lbintoNm(500)
Nm =
56.5000
Q.7 write a user-defined MATLAB function that determines the angle of a triangle
when the length of the sides are given. For the function nameand arguments 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] = triangle(a,b,c)
al=acosd(a.^2+b.^2-c.^2)./2*a*b;
bet=acosd(b.^2+c.^2-a.^2)./2*b*c;
gam=acosd(c.^2+a.^2-b.^2)./2*c*a;
end
>>triangle(10,15,7)
al =
26.6002
>>triangle(6,8,10)
bet =
12.9535
>>triangle(200,75,250)
gam =
1.1496e+63
Assignment-4
Programming in MATLAB
Q.1 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+20/4
Sol. a) 5<=8-3
5<=5
Ans =1
>> 5<=8-3
ans =
1
b) y = 7<3-1+6>2
=7<9-1>2
=7<8>2
=1>2
0
>> 7<3-1+6>2
ans =
0
c) y=(7<3)-1+(6>2)
=0-1+1
=0
>> y=(7<3)-1+(6>2)
y=
0
d) y=2*4+5==7+20/4
2*4+5==7+5
8+5==7+7
13==12
y=0
>> y=2*4+5==7+20/4
y=
0
Q.2 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<=b/2
c) y =a-(b<=b/2)
>> a =10;
>> b =6;
>> y = a>=b
y=
1
b) a=10, b=6
y =a-b<=b/2
=10-6<=6/3
=10-6<=2
=4<=2
y=0
>> a=10;
>> b=6;
>> y =a-b<=b/2
y=
0
c) a=10, b=6
y=a-(b<=b/2)
=10-(6<=6/2)
=10-(6<=3)
=10-0
=10
>> a=10;
>> b=6;
>> y=a-(b<=b/2)
y=
10
b) w~=v
[0 2 1 -1 0 -2 4 3 2]~= [4 -2 -1 5 0 1 -3 8 2]
Ans =
1 1 1 1 0 1 1 1 0
Q.5 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)
sol. a)
ans =1
>> 5&-2
ans =
1
b)
8-2|6+5&~2
=8-2|6+5&0
=8-2|6+0
=6|6
=1
>> 8-2|6+5&~2
ans =
1
c) ~(4&0)+8*~(4|0)
=~(0)+8*~(1)
=1+8*0
1
>> ~(4&0)+8*~(4|0)
ans =
1