Matlab Manual 1st Sem (24-25)
Matlab Manual 1st Sem (24-25)
Prepared by:
Department of Mathematics
Vidyavardhaka College of Engineering
Mysuru
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
1. Command Window
2. Command History
3. Workspace
4. Current Directory
5. Help Browser
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
Note: Any line that starts with % is a comment and turns green. It doesn’t execute.
Arithmetic Operations
Difference between the commands format short, format long, format bank, and format rat
*******
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
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
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.
*****
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)
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)
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")
legend("a","b","c")
'o' Circle
'red' 'r'
'green' 'g'
'blue' 'b'
'cyan' 'c'
'magenta' 'm'
'yellow' 'y'
'black' 'k'
'white' 'w'
*******
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]).
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)
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.
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.
*****
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
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.
*******
syms s t
f = sin(s*t);
The result is
ans =
s*cos(s*t)
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.
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)
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')
*******
fplot(sol,[0 5])
xlabel('time (minutes)'); ylabel('temperature (\circC)')
******
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.
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.
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
*******
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.
F = int(expr,var,a,b) computes the definite integral of expr with respect to the symbolic scalar
variable var from a to 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])
π 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
∞
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.
*****