0% found this document useful (0 votes)
21 views32 pages

Matlab Manual 1st Sem (24-25)

Uploaded by

vardhanacpb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views32 pages

Matlab Manual 1st Sem (24-25)

Uploaded by

vardhanacpb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

MATLAB Manual

For I Semester BE Students


ACADEMIC YEAR 2024-25

Prepared by:
Department of Mathematics
Vidyavardhaka College of Engineering
Mysuru

VVCE, Mysuru Page 1


Contents
Experiment No. Title of the Experiment Page No.
Introduction to MATLAB 3
Experiment 01 Matrix Theory 8
Experiment 02 Algebra of Matrices and Plotting of Vectors 12
Experiment 03 Symbolic variables, Functions and Derivatives 17
Experiment 04 Maclaurin’s Series Expansion 20

Experiment 05 Solving Linear Differential equations using dsolve


22
operator
Experiment 06 Partial Derivatives, Jacobians and Polar curves 25
Experiment 07 Introduction to Control Structures 26
Experiment 08 Evaluation of Double Integrals 29
Open ended experiment 01 Solving system of Linear equations (For all)
Euclid Algorithm (CSE Stream)
Open ended experiment 02
Newton-Raphson Method (ME, CIVIL, EC Stream)

VVCE, Mysuru Page 2


INTRODUCTION TO MATLAB

GETTING STARTED WITH MATLAB

What is MATLAB?

MATLAB is an efficient user-friendly interactive software package, which is very effective for
solving engineering, mathematical, and system problems.

MATLAB Windows
The assumption here is that the reader is sitting in front of an active computer and MATLAB is
installed.

To begin MATLAB, double click the MATLAB icon on the computer’s desktop or select MATLAB
from the Start or Program menu. Immediately a special window called the MATLAB desktop
appears as below

The MATLAB desktop consists of the following major components:

1. Command Window
2. Command History
3. Workspace
4. Current Directory
5. Help Browser

VVCE, Mysuru Page 3


The command window is a place where certain basic operations like simple mathematical
calculations can be easily performed. The difficulty with command prompt is that previously
typed lines cannot be modified.

Command history provides all the details of the functions typed and codes executed from the
command prompt in the recent past.

Workspace includes the names of variables generated during the running of certain
functions or codes. It also includes details regarding the size and types of variables generated.
The current directory shows the location where the program is held or the directory from
where the current execution is running.

Work folder in the drive where MATLAB is installed is the default folder where programs
are stored.
VVCE, Mysuru Page 4
Help browser is the way to go through the details of the documentation made available
with MATLAB.

The prompt >> is the program prompt indicating that you are in the MATLAB
environment. Each instruction line in the command window begins with a prompt (>>), which is
automatically inserted by MATLAB. An instruction is executed after pressing the enter key. The
result of a command appears on the next line.

The following examples indicates the input-output relations of MATLAB and its response
A MATLAB output

VVCE, Mysuru Page 5


A MATLAB prompt, meaning that the instruction was executed and MATLAB is waiting for the
next command

Note: Any line that starts with % is a comment and turns green. It doesn’t execute.

Arithmetic Operations

The basic operations of MATLAB


MATLAB® can be used as a Calculator to perform basic Arithmetic Operations such as:
Addition (+), Subtraction (-), Multiplication (*), Division (/), Power (^)
There are also three other operators that operate on an element by element basis:
 Multiplication of two vectors, element by element (.*)
 Division of two vectors, element-wise (./)
 Raise all the elements of a vector to a power (.^)

Managing the Workspace

 clear Clears all variables in the MATLAB® workspace


 clear a, b Clears variables a and b
 clc Clears the command window
Symbols Operations Examples Answers
+ Addition A=3+2 A=5
- Subtraction A=3-2 A=1
* Multiplication A=3*2 A=6
^ Exponentiation A=3^2 A=9
/ Right division A=6/3 A=2
\ Left division A=3/6 A=2

Difference between the commands format short, format long, format bank, and format rat

We can change the format to format long by typing


>>format long
View the result of value of by typing
>>sqrt(3)
ans
= 1.732050807568877
When the format is set to format short

VVCE, Mysuru Page 6


>>format short
>> sqrt(3)
ans
= 1.7321

When the format is set to format bank


>>format bank
>> sqrt(3)
ans
= 1.73

When the format is set to format rat


>> format rat
>> sqrt(3)
ans
= 1351/780

Difference between commands fix, round, ceil and floor


>> round(6.628)
ans
=7
% round command rounds the element of x to towards nearest integer
>> fix(6.628)
ans
=6
% fix command rounds the element x to nearest integer towards zero
>> ceil(6.628)
ans
=7
% ceil command rounds the element x to nearest integer towards infinity
>> floor(6.628)
ans
=6
% floor command rounds the element x to nearest integer towards minus infinity

*******

VVCE, Mysuru Page 7


Experiment 01
Matrix Theory
Arrays and Matrices
Creating Row vectors
We create arrays with multiple elements using square brackets.
x = [3 5]
Creating Column vectors
Create a column vector by separating each element by a semi-colon.
y = [3; 5]
Creating vectors with evenly spaced numbers
To create a vector starting at n and ending at m we write n:m
a=5:8
Note: the (:) operator uses a default spacing of 1, and we can specify a required spacing as
follow:
b=1:2:11
c=1:3:10
Creating Matrices
A n-by-m matrix can be created by separating each row by a semi-colon.
x = [3 4 5; 6 7 8]
Creating Matrices with random numbers
rand(n) will give a n-by-n matrix with random entries between 0 and 1
p=rand(2)
rand(n,m) will give a n-by-m matrix with random entries between 0 and 1
q=rand(3,2)

Few Useful Matrix Commands

zeros(m,n) creates an m x n matrix of all zeros


zeros(n) creates an n x n matrix of zeros
ones(m,n) creates an m x n matrix of all ones
ones(n) creates an n x n matrix of ones
eye(n) creates an n x n identity matrix (all zeros but ones on the diagonal) numel(vec) returns
the number of elements in the vector
numel(mat) returns the total number of elements in the matrix (the product of the number of
rows and the number of columns)
length(vec) returns the number of elements in the vector
length(mat) returns either the number of rows or the number of columns in the matrix,
whichever is larger
size(mat) returns the number of rows and the number of columns of the matrix

VVCE, Mysuru Page 8


linspace function
If we know the number of elements we want in a vector (instead of the spacing between
each element), we could instead use the linspace function:

linspace(first,last,number_of_elements).

x = linspace(0,1,5)
x=
0 0.250 0.500 0.750 1.000

Both linspace and the : operator create row vectors. However, we can convert a row
vector into a column vector using the transpose operator (').
x = 1:3;
x = x'
x=
1
2
3
 We can create column vectors in a single command by creating the row vector and
transposing it all on one line. Note the use of parentheses here to specify the order of
operations.
x = (1:2:5)'
x=
1
3
5

Creating Matrices with random numbers


MATLAB contains many functions that help us to create commonly used matrices, such
as matrices of random numbers.
x = rand(2)
x=
0.8147 0.1270
0.9058 0.9134
Note that the 2 in the command rand(2) specifies that the output will be a 2-by-2 matrix of
random numbers.
Many matrix creation functions allow us to input one number to create a square matrix (n-
by-n) or input two numbers to create non square matrices.
x = rand(2)
x=

VVCE, Mysuru Page 9


0.8147 0.1270
0.9058 0.9134

x = rand(2,3)
x=
0.6324 0.2785 0.9575
0.0975 0.5469 0.9649

Most array creation functions accept the same inputs as rand. For example, the zeros
and ones functions create matrices of all zeros or ones, respectively.
x = ones(2,3)
x=
1 1 1
1 1 1

Extraction of values from a Matrix


Let A be any random matrix of large size.
We can extract values from an array using row, column indexing.
y = A(5,7)
This syntax extracts the value in the 5th row and 7th column of A and assigns the result to the
variable y.
We can use the MATLAB keyword end as either a row or column index to reference the last
element.
y = A(end,2)
Note that we can use arithmetic with the keyword end. For example:
y = A(end-1,end-2)

Extraction of rows and columns from a Matrix


When used as an index, the colon operator (:) specifies all the elements in that dimension.
For example
x = A (2,:) creates a row vector containing all of the elements from the second row of A.

Note: The colon operator can refer to a range of values.


For example
x = A (1:3,:) syntax creates a matrix containing the first, second, and third rows of the matrix A.
A single index value can be used to reference vector elements.
For example
x = v(3) returns the third element of vector v when v is either a row or column vector.
Elements of a variable can be altered by combining indexing with assignment.

VVCE, Mysuru Page 10


For example:
v(2) = 11 changes the 2nd element of the vector v to 11.
EXERCISE

Task 01
a) Create an array named x1 with two elements: 7 and 9
b) Create an array named y1 with two elements, 7 and 9, in a single column.
c) Create a row vector named y2 that contains the values 3, 10, and 5 in that order.
d) Create a column vector named y3 that contains the values 8, 2, and -4 in that order.
Task 02
a) Create a row vector named a1 that contains the values 1, 2, and 3, in that order.
b) Create a row vector named a2 with the values 1, 2, 3, and 4, but this time using the
: operator
c) Create a row vector named a3 that starts at 1, ends at 5, and each element is separated
by 0.5.
d) Create a row vector named a4 that starts at 3 and ends at 13, with each element
separated by 2.
Task 03
a) Create a matrix named x with the values shown below.
5 6 7
8 9 10
Task 04
a) Create a row vector named x that contains the values 1, 2, and 3, in that order.
b) Create a row vector named x with the values 1, 2, 3, and 4, but this time using the :
operator
c) Create a row vector named x that starts at 1, ends at 5, and each element is separated
by 0.5.
d) Create a row vector named x that starts at 3 and ends at 13, with each element
separated by 2.

Task 05
a) Create a row vector named x that starts at 1, ends at 10, and contains 5 elements.
b) Transpose x from a row vector to a column vector using the transpose operator.
c) In a single command, create a column vector named x that starts at 5, ends at 9 and has
elements that are spaced by 2.

*****

VVCE, Mysuru Page 11


Experiment 2
Algebra of Matrices and Plotting of Vectors

Algebra of Matrices
MATLAB is designed to work naturally with arrays.
For example, we can add a scalar value to all the elements of an array.
x = [1 2 3];
y=x+2
y=
3 4 5
We can add together any two arrays of the same size.
z=x+y
We can multiply or divide all of the elements of an array by a scalar.
z = 2*x
y = x/3
The maximum value of a vector can be determined using the max function.
xMax = max(x)
The * operator performs multiplication of two matrices.
A = [1 2 0; 2 5 -1; 4 10 -1]& B = A'
C=A*B
C=
5 12 24
12 30 59
24 59 117
The .* operator performs elementwise multiplication and allows us to multiply the
corresponding elements of two equally sized arrays.
z = [3 4] .* [10 20]
z=
30 80
The size function can be applied to an array to produce a single output variable containing the
array size.
s = size(x)
The size function can be applied to a matrix to produce either a single output variable or two
output variables. Use square brackets ([ ]) to obtain more than one output.
[xrow,xcol] = size(x)
The maximum value of a vector and its corresponding index value can be determined using the
max function. The first output from the max function is the maximum value of the input vector.
When called with two outputs, the second output is the index value.
[xMax,idx] = max(x)

VVCE, Mysuru Page 12


Some useful Matrix functions
Assuming a vector variable “vec”, matrix variable “mat” and square matrix “squaremat”
 zeros(m,n) creates an m x n matrix of all zeros
 zeros(n) creates an n x n matrix of zeros
 ones(m,n) creates an m x n matrix of all ones
 ones(n) creates an n x n matrix of ones
 eye(n) creates an n x n identity matrix (all zeros but ones on the diagonal)
 magic(n) creates an n x n magic matrix (sum of all rows, columns, and diagonal are the
same)
 rand(n) creates an n x n matrix of random real numbers, each in the range from 0 to 1
 numel(vec) returns the number of elements in the vector
 numel(mat) returns the total number of elements in the matrix (the product of the number
of rows and the number of columns)
 length(vec) returns the number of elements in the vector
 length(mat) returns either the number of rows or the number of columns in the matrix,
whichever is larger
 size(mat) returns the number of rows and the number of columns of the matrix
 size(vec) returns the number of rows and the number of columns of the vector
 rand(m,n) creates an m x n matrix of random numbers, each in the range from 0 to 1
 rank(mat) returns the rank of matrix mat
 trace(A) returns the trace of a square matrix A
 diag(A) returns the diagonal of a square matrix A as a vector
 diag(vec) creates a diagonal matrix by creating a matrix of all zeros and putting the vector
“vec” on the diagonal
 triu(mat) will create an upper triangular matrix from mat
 tril(mat) will create an lower triangular matrix from mat
 det(A) gives the determinant of a square matrix A
 inv(A) gives the inverse of a matrix A if exists
 eig(A) gives the eigen values of the matrix A

VVCE, Mysuru Page 13


 [V E]=eig(A) gives two matrices V and E, where the columns of V are a set of linearly
independent eigenvectors and the diagonal elements of E are the eigenvalues of A.
Plotting of vectors
Two vectors of the same length can be plotted against each other using the plot function.
plot(x,y)
The plot function accepts an additional argument that allows us to specify the color, line style,
and marker style using different symbols in single quotes.
plot(x,y,"r--o")
The command above plots a red (r) dashed (--) line with a circle (o) as a marker.
Notice that each plot command created a separate plot. To plot one line on top of another, use
the hold on command to hold the previous plot while we add another line.

plot(x1,y1)
hold on
plot(x2,y2)
While the hold state is on, plots will continue to go on the same axes. To return to the default
plot behavior, where each plot gets its own axes, enter hold off.

When we plot a single vector by itself, MATLAB uses the vector values as the y-axis data and
sets the x-axis data to range from 1 to n (the number of elements in the vector).

The plot function accepts optional additional inputs consisting of a property name and an
associated value.
plot(y,"LineWidth",5)

The command above plots a heavy line.

We can provide additional inputs to the plot function after the line specifier.

plot(x,y,"ro-","LineWidth",5)

Labels can be added to plots using plot annotation functions, such as title. The input to these
functions is a string. Strings in MATLAB are enclosed in double quotes (").
title("Plot Title")

We can add a legend to our plot using the legend function.

legend("a","b","c")

VVCE, Mysuru Page 14


Additional Inputs in Plots:

Line Style Description Resulting Line

'-' Solid line

'--' Dashed line


':' Dotted line
'-.' Dash-dotted line

Marker Description Resulting Marker

'o' Circle

'+' Plus sign


'*' Asterisk
'.' Point
'x' Cross
'_' Horizontal line
'|' Vertical line
's' Square
'd' Diamond
'^' Upward-pointing triangle
'v' Downward-pointing triangle
'>' Right-pointing triangle
'<' Left-pointing triangle
'p' Pentagram
'h' Hexagram

VVCE, Mysuru Page 15


Color Name Short Name Appearance

'red' 'r'

'green' 'g'

'blue' 'b'

'cyan' 'c'

'magenta' 'm'

'yellow' 'y'

'black' 'k'

'white' 'w'

*******

VVCE, Mysuru Page 16


Experiment 03
Symbolic variables, Functions and Derivatives

Symbolic variables
To create a symbolic variable without assigning it a value, use the syms command followed by
the variable name.
Example 1: To create a symbolic variable ‘x’, type
syms x
Example 2: To create symbolic variables ‘a’, ‘b’, & ‘c’ type
syms a b c
Symbolic expression:
A symbolic expression is defined in terms of other symbolic variables. For example, the
command y=3∗x 3 creates an expression 3 x 3 and stores it in the symbolic variable y.

Instructions:

1. The fplot function can be used to visualize expressions with one variable.

fplot(expression)
2. Use the command grid on to add grid lines to our plot to help us visualize the y-intercept.
3. To visualize ‘expressionA’ and ‘expressionB’ together, use the hold on command to add
to our current plot. Also, use the hold off command when we are finished adding to our
plot.
fplot(expressionA)
hold on
fplot(expressionB)
hold off
4. By default, fplot plots over the interval -5 to 5 on the x-axis. To change the interval, a
second input can be provided to fplot with the desired interval in square brackets. For
example, to plot over the interval -10 to 10, use fplot(expression,[-10 10]).

VVCE, Mysuru Page 17


EXERCISE

1. Create the expression x2+5x+6 and store it in expr.

2. Create symbolic variables a, b and c. Then create an expression y for a general second
order polynomial ax2+bx+c
3x
3. Create the expression +4 and store it in ‘yLinear’. Use fplot to visualize yLinear.
2
3
x
4. Create the expression −2 x +3 and store it in ‘yCubic’. Use fplot to visualize yCubic.
2
Add a plot of yLinear to our plot of yCubic. Use fplot to visualize yCubic. Also, plot yCubic
from -1 to 3.

Differentiation
To illustrate how to find derivatives using Symbolic Math Toolbox software, first we create a
symbolic expression:
syms x
f = sin(5*x);
Note: diff is the differentiate symbolic expression or function
The following command differentiates f with respect to x:
f_x=diff(f)
Output: f_x =
5*cos(5*x)
As another example, let us consider the following function:
g = exp(x)*cos(x);
where exp(x) denotes ex, and differentiate g:
y = diff(g)
Output: y=
exp(x)*cos(x) - exp(x)*sin(x)

Derivatives at a given value


To find the derivative of g for a given value of x, substitute x for the value using subs and return
a numerical value using vpa. Find the derivative of g at x = 2.
vpa(subs(y,x,2))
ans =
VVCE, Mysuru Page 18
-9.7937820180676088383807818261614

Higher Derivatives
Df=diff(f,n) computes the nth derivative of f with respect to the symbolic variable determined
by symvar.
Df=diff(f,var) differentiates f with respect to the differentiation parameter var. var can be a
symbolic scalar variable, such as x, a symbolic function, such as f(x), or a derivative function,
such as diff(f(t),t).
Df=diff(f,var,n) computes the nth derivative of f with respect to var.

To take the second derivative of g, enter


diff(g,2)
ans =
-2*exp(x)*sin(x)
We can get the same result by taking the derivative twice:
diff(diff(g))
ans =
-2*exp(x)*sin(x)

EXERCISE
1. Find the derivative of y=x 3 w.r.t. x
2. Find the derivative of y=sin ⁡(5 x) w.r.t. x and store it as y_x and plot the graph of y and
y_x in the interval [−4 , 4].
3. Find the second order derivative of f =e x cos ⁡( x) at x=2 and store the output as f_2.
4. Find the derivative of the function sin( x2 ). Find the value of the derivative at x=2.
Convert the value to double.

*****

VVCE, Mysuru Page 19


Module 04
Maclaurin’s Series Expansion
A Taylor polynomial approximates a function near a known value. We can evaluate the
polynomial at nearby points to get an approximate value for the function.
For a function f(t), we can use the taylor function to find the Taylor polynomial for f near the
point t = 3.
tpoly = taylor(f,t,3)
1. Obtain Maclaurin’s series expansion of f (t)=log(1+t).
Command
clearvars
syms t
g(t)=sin(t)
h=taylor(g,t,0)

Note: The taylor function returned a 5th degree polynomial, but we can return a higher or lower
degree polynomial by specifying the truncation order.
tpoly = taylor(f,t,3,'order',n)
The truncation order n is one more than the highest polynomial degree we want. So if we want a
polynomial of degree ≤ 7, use a truncation order of 8.

2. Obtain Maclaurin’s series expansion of f (t)=sin ⁡(t) upto the term containingt 7& plot
the graph of the functions on a single plot.
Command:
clearvars
syms t
g(t)=sin(t)
h=taylor(g,t,0,'order',8)
fplot(h)
hold on
fplot(g)

3. Obtain Maclaurin’s series expansion of g(t )=e t−1 up to the term containing t 9 and plot
the graphs.
Command:
syms t
g(t)=exp(t-1)
h=taylor(g,t,0, 'order',10)
fplot(g)
hold on

VVCE, Mysuru Page 20


fplot(h)

EXERCISE
1. Obtain Maclaurin’s series expansion of g(x )=e x upto the term containing x 6 and store it
as h. Also, obtain the graphs.
2. Obtain Maclaurin’s series expansion of g(x )=cos ⁡(x ) and plot the graphs.
3. Obtain Maclaurin’s series expansion of g(x )=sin( x) and plot the graphs.

*******

VVCE, Mysuru Page 21


Experiment 05
Partial Derivatives, Jacobians and Polar curves

Derivatives of Expressions with Several Variables


To differentiate an expression that contains more than one symbolic variable, specify
the variable that we want to differentiate with respect to. The diff command then calculates the
partial derivative of the expression with respect to that variable.

For example, given the symbolic expression

syms s t
f = sin(s*t);

the command diff(f,t) calculates the partial derivative ∂f/∂t.

The result is

ans =
s*cos(s*t)

To differentiate f with respect to the variable s, enter diff(f,s) which returns:

ans =
t*cos(s*t)

Jacobians
jacobian(f,v) computes the Jacobian matrix of f with respect to v.
∂ (u , v)
Illustration: If u=x2 −2 y & v=x+ y . Find J= .
∂( x , y )
clearvars
syms x y
u=x^2-2*y; v=x+y;
ux=diff(u,x); uy=diff(u,y); vx=diff(v,x); vy=diff(v,y);
J=jacobian([u v],[x y])
Jacobian=det(J)
Note that, the jacobian gives us the matrix of the partial derivatives of the given
functions. In order to find the Jacobian, we need to evaluate the determinant of the above
output matrix.

VVCE, Mysuru Page 22


Note: simplify(expr) performs algebraic simplification of expr. If expr is a symbolic vector or
matrix, this function simplifies each element of expr.

Exercise:
1. Calculate the partial derivatives of
a. f =sin(st ) w.r.t. s b) f =sin(st ) with respect to t.
2. Let u=a x 2+2 hxy +b y 2 . Evaluate the second order partial derivative of u w.r.t. x at a=2.
3. Find z x , z y , z xy , z xx , z yy where z=x 3 + y 3−3 xy .
∂( x , y , z )
4. If x=r cos ( s ) cos ⁡(t ), y=r cos ( s ) sin ⁡(t) & z=r sin ( s ) Find J= .
∂(r , s ,t)

5. Ifu=x+3 y 2−z 3 , v=4 x 3 yz & w=2 z 2−xy . Find J=


∂(u , v , w)
.
∂(x , y , z )

Polar Curves and their plotting


The polar coordinate system is a two-dimensional coordinate system in which each point on a
plane is determined by a distance from a reference point and an angle from a reference
direction

Question:
MATLAB CODE
t=linspace(0,2*pi,100);
r=2*cos(t);
polarplot(t,r)
hold on
r1=2*sin(t);
polarplot(t,r1)
hold on
r2=-r;
polarplot(t,r2)
hold on
r3=-r1;
polarplot(t,r3)

Polar Plot
Question:
VVCE, Mysuru Page 23
MATLAB CODE
theta = 0:0.01:2*pi;
rho = sin(2*theta).*cos(2*theta);
polarplot(theta,rho)

Question:

MATLAB CODE
theta = 0:0.01:2*pi;
rho = (1+cos(theta));
polarplot(theta,rho)

Question:
MATLAB CODE
theta=linspace(0,2*pi,200);
r1=1-sin(theta);
r2=1-cos(theta);
polarplot(theta,r1,'r',theta,r2,'b')

*******

VVCE, Mysuru Page 24


Experiment 06
Solving Linear Differential equations using dsolve operator

A differential equation is an equation containing a dependent variable and independent


variable where the equation involves the derivative of the dependent variable.

Solving Differential Equation


dy
Solve this differential equation =xy
dx
Instructions
1. To define a symbolic differential equation, first create the function using syms.
2. To create the equation, Use the diff function for the derivatives.
3. The dsolve function is used to solve differential equations symbolically.
Commands
syms y(x)
diffEqn = diff(y,x) == y + 9*x
solution = dsolve(diffEqn)

Solving Differential Equation with Initial Conditions


dy
Solve = y +9 x with y (0)=1 and the plot the graph of the solution in the interval [0 ,5 ]
dx
Instruction
In addition to the previous instructions, to determine the constant’s value, we’ll use the initial
condition given. Differential equations with initial conditions can be solved by using dsolve with
the initial condition as the second input.
Commands
syms y(x)
diffEqn = diff(y,x) == y + 9*x
solution = dsolve(diffEqn); ic=y(0)==1;
sol = dsolve(diffEqn,ic)

Plotting the graph of the above solution,

fplot(sol,[0 5])
xlabel('time (minutes)'); ylabel('temperature (\circC)')

******

VVCE, Mysuru Page 25


Experiment 07
Control Structure
The if Statement

The if statement’s basic form is


if logical expression
statements
end
Every if statement must have an accompanying end statement. The end statement marks the
end of the statements that are to be executed if the logical expression is true.

The else statement

The basic structure for the use of the else statement is


if logical expression
statement group 1
else
statement group 2
end

For example, if we fail to recognize how the test works, the following statements do not
perform the way we might expect.
x = [4,-9,25];
if x < 0
disp(’Some elements of x are negative.’)
else
y = sqrt(x)
end
Because the test if x < 0 is false, when this program is run it gives the result
y=
2 0 + 3.000i
Instead, consider what happens if we test for x positive.
x = [4,-9,25];
if x >= 0
y = sqrt(x)
else
disp(’Some elements of x are negative.’)
end
When executed, it produces the following message:
Some elements of x are negative.

VVCE, Mysuru Page 26


The test if x < 0 is false, and the test if x >= 0 also returns a false value because x >= 0 returns
the vector [1,0,1].

The elseif Statement

The general form of the if statement is


if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end

The else and elseif statements may be omitted if not required. However, if both are used, the
else statement must come after the elseif statement to take care of all conditions that might be
unaccounted for.
For example, suppose that y = log(x) for x > 10, y = sqrt(x) for 0 <= x <= 10, and y = exp(x) - 1 for
x < 0. The following statements will compute y if x already has a scalar value.

if x > 10
y = log(x)
elseif x >= 0
y = sqrt(x)
else
y = exp(x) - 1
end

for loop
A simple example of a for loop is
for k = 5:10:35
x = k^2
end

The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each
successive pass through the loop increments k by 10 and calculates x until k exceeds 35. Thus, k
takes on the values 5, 15, 25, and 35, and x takes on the values 25, 225, 625, and 1225. The
program then continues to execute any statements following the end statement.
Note the following rules when using for loops with the loop variable expression k = m:s:n:
• The step value s may be negative.

VVCE, Mysuru Page 27


Example: k = 10:-2:4 produces k = 10, 8, 6, 4.
• If s is omitted, the step value defaults to 1.
• If s is positive, the loop will not be executed if m is greater than n.
• If s is negative, the loop will not be executed if m is less than n.
• If m equals n, the loop will be executed only once.
• If the step value s is not an integer, round-off errors can cause the loop to execute a
different number of passes than intended.

10
Examples: Evaluate the following summation: ∑ i
3

n=0

% filename: for1.m
% Example: Use a for loop to find sum(i^3) for i = 1 to 10.
Sum = 0; %Initialize variable to zero
for i = 1:1:10
Sum = Sum + i^3;
end
fprintf('Sum = %0.0f\n',Sum);
OUTPUT
>>SUM_1
>>Sum = 3025
*******

VVCE, Mysuru Page 28


Experiment 08
Evaluation of Double Integrals

Description
F = int(expr) computes the indefinite integral of expr. int uses the default integration variable
determined by symvar(expr,1). If expr is a constant, then the default integration variable is x.

F = int(expr,var) computes the indefinite integral of expr with respect to the symbolic scalar
variable var.

F = int(expr,a,b) computes the definite integral of expr from a to b. int uses the default
integration variable determined by symvar(expr,1). If expr is a constant, then the default
integration variable is x.

int(expr,[a b]) is equivalent to int(expr,a,b).

F = int(expr,var,a,b) computes the definite integral of expr with respect to the symbolic scalar
variable var from a to b.

int(expr,var,[a b]) is equivalent to int(expr,var,a,b).

Illustrations
1. Find the Integral of y=x 3 sinx w.r.t. x
Command
syms x
f(x) = x^3*sin(x)
int(f(x),x)
fplot(int(f(x),x)

π
2
2. Evaluate: ∫ sin 6 xdx
0

Command
syms x
y = sin(x)^6
int(y,x,[0,pi/2])

VVCE, Mysuru Page 29


VVCE, Mysuru Page 30
∞ ∞ −y
e
3. Evaluate: ∫ ∫ dxdy
0 x y
Command
syms x y
f = exp(-y)/y
int(int(f,y,x,inf),x,0,inf)

π 1 +cosθ

4. Evaluate: ∫ ∫ 2
2 π r sinθdrdθ
0 0

Command
syms r thetha
f = 2*pi*r^2*sin(thetha)
int(int(f,r,0,(1+cos(thetha))),thetha,0,pi)

EXERCISE

1. Evaluate: ∫ (1+ x ) (1−x) dx


11 13

−1


dx
2. Evaluate: ∫ 4
0 1+ x
2 3

3. Evaluate: ∫ (4−x ) dx
2 2

1 2− x

4. Evaluate: ∫ ∫ xy dxdy
0 x
2

a √ x
a

5. Evaluate∫ ∫ (x 2+ y 2) dydx
0 x
a

π
2
6. Evaluate: ∫ sin 7 x cos5 xdx
0

7. Find the area of the region bounded by the curve y=x 2and the lines x=1 , x=4 and the
x-axis.

VVCE, Mysuru Page 31


8. Find the area of the region bounded by the curve y=9 x 2 , x=2 , x=4 and the x-axis in
the first quadrant
2 2
x y
9. Find the area of the region bounded by the ellipse + =1
16 9
10. Find the area of the region in the first quadrant enclosed by x-axis, line x=√ 3 y and the
circle x 2+ y 2=4

*****

VVCE, Mysuru Page 32

You might also like