Introduction to MATLAB
What is MATLAB?
MATLAB (an abbreviation of "MATrix LABoratory") is a multi-paradigm programming
language and numeric computing environment developed by MathWorks.
MATLAB allows matrix manipulations, plotting of functions and data, implementation of
algorithms, creation of user interfaces, and interfacing with programs written in other languages.
How to start MATLAB?
One can enter MATLAB by double-clicking on the MATLAB shortcut icon on Windows desktop .
When MATLAB is started, a special window called the MATLAB desktop appears which consists of
following sub-windows:
Command Window- This is the main part of the window where commands can be entered. It is
indicated by the command prompt (>>).
Current Folder- The files created in MATLAB are saved in current directory. The saved files can be
viewed and accessed for further use.
Workspace- The workspace shows all the variables created and/or imported from files and
displays type and size of the variables.
Command History- The commands typed in the command window automatically get recorded
and stored in command history day wise. These can be retrieved any time for execution. The
command history gets cleaned only when the command ‘Clear Command History’ is used.
Figure MATLAB Desktop
How to open and save files?
In the toolbar of MATLAB window, the options ‘HOME’ or ‘EDITOR/LIVE EDITOR’ possess the
icon which is to ‘open’ a file with ‘.m’ or ‘.mlx’ extension. The particular file gets loaded in editor
window once it is clicked on. All DOS commands are also applicable. A click on the icon saves the
file.
Arithmetic Operations:
Understand how to use MATLAB as a calculator to carry out arithmetic operations such as
addition, subtraction, multiplication, division and exponentiation.
Use format commands to control floating point output display.
Execute arithmetic expressions involving various operations.
Arithmetic OperatorsandSpecial Characters
Operations Symbol Examples Operations Symbol Examples
Addition + 4+3=7 Right division / 1/2
Subtraction − 5−3=2 Left division \ 4\8 = 8/4 = 2
Multiplication * 6 ∗ 7 = 42 Exponentiation ˄ 53 =125
Some mathematical symbols:
1. pi - π 2. Inf - ∞ 3. i(or j) - 1
ArrayOperations:
Array operations work on corresponding elements of arrays with equal dimensions. Each element in
the first operand gets matched up with the element in the same location in the second operand. The
following table provides a summary of arithmetic array operators in MATLAB.
Arithmeticarrayoperators
Operator Purpose Description
+ Addition A + B adds A and B
+ Unary plus +A returns A
− Subtraction A − B subtracts B from A
− Unary minus −A negates the elements of A
.∗ Element-wise A. ∗ B is the element-by-element product of A and
.ˆ multiplication
Element-wise power A.ˆBB is the matrix with elements A(i, j) to the B(i, j)
./ Right array division power A./B is the matrix with elements A(i, j)/B(i, j)
.′ Array transpose A.′ is the array transpose of A.
PROGRAM 1: Solution of first order differential equation and plotting the solution curves
Aim: Find the solution of first order differential equation and also plot the curves for solution obtained.
Description: S = dsolve(eqn) solves the differential equation eqn, where eqn is a symbolic equation.
Use diff and == to represent differential equations. For example, diff(y,x) == y represents the
equation dy/dx = y. Solve a system of differential equations by specifying eqn as a vector of those
equations.
Example 1: Solve the first order differential equation dy/dx = xy and plot the graph.
MATLAB code:
Output
Syntax to plot the graph:
Example 2: Solve the first order differential equation and plot the graph.
MATLAB code:
Output
Syntax to plot the graph :
Example 3: Solve
MATLAB code:
Output:
Syntax to plot the graph:
Plot:
PROGRAM 2: Solution of differential equations with initial conditions.
Aim: Find the solution of higher order differential equation with given initial conditions.
Description: S = dsolve(eqn,cond) solves eqn with the initial or boundary condition cond.
Use diff and == to represent differential equations.
�2 �
Example 1 -Solve the second-order differential equation ��2
= �� with the initial
conditions y(0)=0 and y′(0)=1..
MATLAB code:
syms y(t) a
eqn = diff(y,t,2) == a*y;
Dy = diff(y,t);
cond = [y(0)==0, Dy(0)==1];
ySol(t) = dsolve(eqn,cond)
Output:
�2 �
Example 2: Solve the second-order differential equation ��2
= �2 � with the initial
conditions y(0)=b and y′(0)=1.
MATLAB code:
syms y(t) a b
eqn = diff(y,t,2) == a^2*y;
Dy = diff(y,t);
cond = [y(0)==b, Dy(0)==1];
ySol(t) = dsolve(eqn,cond)
Output:
Example 3: Solve this second-order differential equation with two initial conditions.
�2 �
��2
= cos 2� − � , y(0)=1, y′(0)=0.
MATLAB code:
syms y(x)
Dy = diff(y);
ode = diff(y,x,2) == cos(2*x)-y;
cond1 = y(0) == 1;
cond2 = Dy(0) == 0;
conds = [cond1 cond2];
ySol(x) = dsolve(ode,conds);
ySol = simplify(ySol)
Output:
PROGRAM 3: Solution of homogeneous ordinary differential equations of higher order.
Aim: Find the solution of homogeneous ordinary differential equations of higher order.
Description: A first order Differential Equation is Homogeneous when it can be in this form: dy/dx=F(y/x).
In Matlab, we use cond=[cond1 cond2] Sol = dsolve(ode,cond), finalSol = simplify(Sol)
solves eqn with the initial or boundary condition cond.Use diff and == to represent differential
equations.
Example 1: Solve the second order homogeneous differential equation 2x2d2y/dx2 +3x dy/dx -y = 0.
MATLAB code:
syms y(x)
ode = 2*x^2*diff(y,x,2)+3*x*diff(y,x) - y == 0;
ySol(x) = dsolve(ode)
Output:
Example 2: Solve the third-order differential equation d3u /dx3 - u=0 with three initial conditions.
u(0) = 1, u′(0) = −1, u′′(0) = π.
MATLAB code:
syms u(x)
Du = diff(u,x);
D2u = diff(u,x,2);
ode = diff(u,x,3) - u == 0;
cond1 = u(0) == 1;
cond2 = Du(0) == -1;
cond3 = D2u(0) == pi;
conds = [cond1 cond2 cond3];
uSol(x) = dsolve(ode,conds)
Output:
Example 3: Solve the second-order differential equation (Puiseux series),
(x2 + 1)d2y/dx2 – 2 x dy/dx + y = 0, with the initial conditions y(0) = 5, y′(0) = a.
MATLAB code:
syms y(x) a
ode = (x^2+1)*diff(y,x,2)-2*x*diff(y,x)+y == 0;
Dy = diff(y,x);
cond = [Dy(0) == a; y(0) == 5];
ySol(x) = dsolve(ode,cond,'ExpansionPoint',0)
Output:
PROGRAM 4: Solution of non-homogeneous ordinary differential equations of higher order.
Aim: Find the solution of non- homogeneous ordinary differential equations of higher order.
Description: Non-homogeneous differential equations are simply differential equations that do not satisfy the
conditions for homogeneous equations. This means that non-homogenous differential equations are
differential equations that have a function on the right-hand side of their equation.
In Matlab, we use cond=[cond1 cond2] Sol = dsolve(ode,cond), finalSol = simplify(Sol)
solves eqn with the initial or boundary condition cond.Use diff and == to represent differential
equations.
Example 1: Solve the second-order differential equation with two initial conditions:
d2y/dx2 +4*y= x*sin(x)+sin(2*x), y(0) = 1, y′(0) = 0.
MATLAB code:
syms y(x)
Dy = diff(y);
ode = diff(y,x,2)+4*y == x*sin(x)+sin(2*x);
cond1 = y(0) == 1;
cond2 = Dy(0) == 0;
conds = [cond1 cond2];
ySol(x) = dsolve(ode,conds);
ySol = simplify(ySol)
Output:
Example 2: Solve the second-order differential equation (Airy equation) d2y/dx2 = xy.
MATLAB code:
syms y(x)
ode = diff(y,x,2) == x*y;
ySol(x) = dsolve(ode)
Output:
Example 3: Solve the second-order differential equation (Airy equation) d2y/dx2+ dy/dx = sin(x) + y.
MATLAB code:
syms y(x)
Dy = diff(y);
ode = diff(y,x,2)+diff(y,x) == sin(2*x)+y;
ySol(x) = dsolve(ode);
ySol = simplify(ySol)
Output:
PROGRAM_5: Interpolation/Extrapolation using Newton’s forward and backward difference
formulae.
Aim: Find the approximate value from the given data using Newton's forward and backward
interpolation formula
Description: Newton's forward and backward interpolation formulas are used to estimate the value of
a function between known data points, with the forward formula suitable for values near the
beginning of the table and the backward formula for values near the end.
NEWTON'S FORWARD INTERPOLATION FORMULA
p p 1 p p 1 p 2
y p y0 py0 2 y0 3 y0 ...
2! 3!
x x0
where p
h
NEWTON'S BACKWARD INTERPOLATION FORMULA
p p 1 2 p p 1 p 2 3
y p yn pyn yn yn ...
2! 3!
x xn
where p
h
Example 1: Write the MATLAB code that uses Newton's forward interpolation formula and find the
approximate value of f(9) given the following data points (x,y) = (8,10), (10,19), (12,32.5), (14,54),
(16,89.5) & (18,154).
MATLAB code:
clc;
clear all;
x=[8,10,12,14,16,18];
y=[10,19,32.5,54,89.5,154];
n=length(x);
X=9;
h=x(2)-x(1);
F=zeros(n,n);
F(:,1)=y;
for j=2:n
for i=j:n
F(i,j)=F(i,j-1)-F(i-1,j-1);
end
end
p=(X-x(1))/h;
d=F(1,1)+p*F(2,2)+p*(p-1)*F(3,3)/factorial(2)+p*(p-1)*(p-2)*F(4,4)/factorial(3)+p*(p-1)*(p-2)*(p-
3)*F(5,5)/factorial(4)+p*(p-1)*(p-2)*(p-3)*(p-4)*F(6,6)/factorial(5);
fprintf('f(%0.4f)= %0.4f \n', X, d);
Output:
f(9.0000)= 14.2363
Example 2: Write the MATLAB code that uses Newton's backward interpolation formula and find
the approximate value of f(17) given the following data points (x,y) = (8,10), (10,19), (12,32.5),
(14,54), (16,89.5) & (18,154).
MATLAB code:
clc;
clear all;
x=[8,10,12,14,16,18];
y=[10,19,32.5,54,89.5,154];
n=length(x);
X=17;
h=x(2)-x(1);
F=zeros(n,n);
F(:,1)=y;
for j=2:n
for i=j:n
F(i,j)=F(i,j-1)-F(i-1,j-1);
end
end
p=(X-x(n))/h;
d=F(6,1)+p*F(6,2)+p*(p+1)*F(6,3)/factorial(2)+p*(p+1)*(p+2)*F(6,4)/factorial(3)+p*(p+1)*(p+2)*(
p+3)*F(6,5)/factorial(4)+p*(p+1)*(p+2)*(p+3)*(p+4)*F(6,6)/factorial(5);
fprintf('f(%0.4f)= %0.4f \n', X, d);
Output:
f(17.0000)= 116.6582
PROGRAM_6: Computation of area under the curve using Trapezoidal,Simpson’s (1/3)rd and
(3/8)th rules.
Aim: Find the area under the curve using Trapezoidal and Simpson’s (1/3)rd rule
Description: Numerical integration is a process of evaluating or obtaining a definite
b
integral f x dx from a set of numerical values of the integrand f x
a
Trapezoidal rule:
In this method the interval a, b be divided into n equal intervals such that
a x0 x1 x2 ... x n b
xn
h
f x dx 2 f x 2 f x f x f x ... f x f x
x0
0 1 2 3 n 1 n
Simpson 1/3rd rule:
In this method the interval a, b be divided into n (an even number) equal intervals such that
a x0 x1 x2 ... x n b
xn
h
f x dx 3 f x 4 f x f x ... f x 2 f x f x ... f x f x
x0
0 1 3 n 1 2 4 n2 n
3
Example 1: Evaluate 0
(4 + �3 ) dx by using Trapezoidal Rule by taking no. of sub-intervals as
6.
MATLAB code:
clc;
x = 0:0.5:3;
y = sqrt(4+x.^3);
fprintf('The value of the Integral is given by')
I = trapz(x,y)
Output:
The value of integration is 9.3304
1
Example 2: Evaluate 0
( sin x + cos x ) dx by using Simpson’s 1/3rd Rule.
MATLAB code:
clear all;
clc;
f=@(x)(sqrt(sin(x)+cos(x)));
a=input('Enter the lower limit a:');
b=input('Enter the upper limit b:');
n=input('Enter the number of sub-intervals n:');
h=(b-a)/n;
for i=1:1:n-1
y(i)=f(a+i.*h);
end
s_o=0;
s_e=0;
for i=1:1:n-1
if rem(i,2)==0
s_e=s_e+y(i);
else
s_o=s_o+y(i);
end
end
I=(h/3)*(f(a)+f(b)+2*s_e+4*s_o);
fprintf('\n The value of integration is %.4f\n',I);
Output:
Enter the lower limit a:
0
Enter the upper limit b:
1
Enter the number of sub-intervals n:
6
The value of integration is 1.1394
PROGRAM_7: Solution of ODE of first order and first degree by Modified Euler’s method.
Aim: Solve the First order initial value problems using modified Euler’s method.
Description: Modified Euler’s Method: In this method, the tangent is drawn at a point and slope is
calculated for a given step size. Thus this method works best with linear functions.
y E n 1 yn hf xn , yn
h
yn 1 yn
2
f xn , yn f xn 1 , yn 1 E
dy
Example 1: Solve dx = loge (x + y), y 1 = 2 by Modified Euler’s method for � 1.4 taking h=0.1.
Display output for each value of x up to 1.4. Perform 3 modifications at every step.
MATLAB code:
%Euler's Modified
clear
clc
f =@(x,y) log(x+y);
x= 1:0.1:1.4;
y(1)=2;
h=0.1;
for i=2:length(x)
y(i)=y(i-1)+h*f(x(i-1),y(i-1));
y1(i,1)=y(i);
for j=2:4
y1(i,j)=y(i-1)+h/2*(f(x(i),y1(i,j-1))+f(x(i-1),y(i-1)));
end
y(i)=y1(i,4);
end
x=[x(:)];
y=[y(:)];
disp(" x y")
z=[x y];
disp(z)
Output:
Example 2: Apply Modified Euler’s method for � 1.4 taking h=0.1. Display output for each value
of x up to 1.4. Perform 3 modifications at every step.
MATLAB code:
clear
clc
f =@(x,y) 1+(y/x);
x= 1:0.1:1.4;
y(1)=2;
h=0.1;
for i=2:length(x)
y(i)=y(i-1)+h*f(x(i-1),y(i-1));
y1(i,1)=y(i);
for j=2:4
y1(i,j)=y(i-1)+h/2*(f(x(i),y1(i,j-1))+f(x(i-1),y(i-1)));
end
y(i)=y1(i,4);
end
x=[x(:)];
y=[y(:)];
disp(" x y")
z=[x y];
disp(z)
OUTPUT:
PROGRAM_8: Solution of ODE of first order and first degree by 4 t h o r d e r Runge-
Kutta method
Aim: Solve the First order initial value problems using 4th order Runge-Kutta method.
Description: Runge–Kutta Method: The Runge-Kutta method is a reliable and popular approach for
resolving initial-value issues in differential equations,without requiring the high order derivatives of
the functions.
k1 hf xn , y n
h k
k2 hf x n , y n 1
2 2
h k
k3 hf x n , y n 2
2 2
k4 hf x n h , y n k3
1
yn 1 yn k1 2k2 2k3 k 4
6
Example 1: By using 4th order R-K method, solve dy/dx=xy1/3, y(1)=1 at x=1.5 by taking step size as
0.1.
MATLAB code:
clear all;
clc;
f = @(x,y)x.*(y.^(1/3)) ;
x = 1; %initial value of x
y = 1; %initial value of y(x)
h = 0.1; %step size
X = 1.5; %y(1.5)
%X-x
while X-x >= -10^(-10) %smaller value
fprintf("value of y at x = %0.1f is %0.4f \n",x,y);
k1 = h.*f(x,y);
k2 = h.*f(x+h/2,y+k1/2);
k3 = h.*f(x+h/2,y+k2/2);
k4 = h.*f(x+h, y+k3);
k = (k1 + 2.* k2 +2.*k3+k4 )./6;
x =x+h;
y = y+k;
end
OUTPUT:
value of y at x = 1.0 is 1.0000
value of y at x = 1.1 is 1.1068
value of y at x = 1.2 is 1.2279
value of y at x = 1.3 is 1.3641
value of y at x = 1.4 is 1.5166
value of y at x = 1.5 is 1.6862
�
Example 2: By using 4th order R-K method, solve dy/dx = 3x + 2, y(0) = 1 at x = 0.2 by taking step
size as 0.1.
MATLAB code:
clear all;
clc;
f = @(x,y)(3*x+(y/2)) ;
x = 0; %initial value of x
y = 1; %initial value of y(x)
h = 0.1; %step size
X = 0.2; %y(1.5)
%X-x
while X-x >= -10^(-10) %smaller value
fprintf("value of y at x = %0.1f is %0.4f \n",x,y);
k1 = h.*f(x,y);
k2 = h.*f(x+h/2,y+k1/2);
k3 = h.*f(x+h/2,y+k2/2);
k4 = h.*f(x+h, y+k3);
k = (k1 + 2.* k2 +2.*k3+k4 )./6;
x =x+h;
y = y+k;
end
OUTPUT:
value of y at x = 0.0 is 1.0000
value of y at x = 0.1 is 1.0665
value of y at x = 0.2 is 1.1672
PROGRAM_9: Solution of algebraic and transcendental equations by Regula-Falsi method.
Aim: Solve the algebraic and transcendental equations by Regula-Falsi Method.
Description: Regula-Falsi method:
This code solves the non-linear equations using regula-falsi method or false position method with number of
iterations as a stopping criterion. Function takes 3 arguments i.e. x1 and x2 the bracket values and n is the
number of iterations. The code is written in a very simple way and can be easily understood. f.m file is the
function where you can write the desired equations whose roots are ought to be find. Using the formula
Example 1: Find the real root of the equation sinx + cosx + ex = 8 which lies between 2 and 3.
MATLAB code:
syms x;
% Input Section
y = input('Enter non-linear equations: ');
a = input('Enter first guess: ');
b = input('Enter second guess: ');
e = 0.00001 ; %input('Tolerable error: ');
% Finding Functional Value
fa = eval(subs(y,x,a));
fb = eval(subs(y,x,b));
% Implementing the Method
if fa*fb > 0
disp('Given initial values do not bracket the root.');
else
c = (a*fb-b*fa)/(fb-fa);
fc = eval(subs(y,x,c));
fprintf('\n\na\t\t\tb\t\t\tc\t\t\tf(c)\n');
while abs(fc)>e
fprintf('%f\t%f\t%f\t%f\n',a,b,c,fc);
if fa*fc< 0
b =c;
fb = eval(subs(y,x,b));
else
a =c;
fa = eval(subs(y,x,a));
End
c = (a*fb-b*fa)/(fb-fa);
fc = eval(subs(y,x,c));
end
fprintf('\nRoot is: %f\n', c);
end
OUTPUT:
Enter non-linear equations:
sin(x)+cos(x)+exp(x)-8
Enter first guess:
2
Enter second guess:
3
Example 2: Find the real root of the equation �2 − ���� = 12 which lies between 3 and 4.
MATLAB code:
syms x;
% Input Section
y = input('Enter non-linear equations: ');
a = input('Enter first guess: ');
b = input('Enter second guess: ');
e = 0.00001 ; %input('Tolerable error: ');
% Finding Functional Value
fa = eval(subs(y,x,a));
fb = eval(subs(y,x,b));
% Implementing the Method
if fa*fb > 0
disp('Given initial values do not bracket the root.');
else
c = (a*fb-b*fa)/(fb-fa);
fc = eval(subs(y,x,c));
fprintf('\n\na\t\t\tb\t\t\tc\t\t\tf(c)\n');
while abs(fc)>e
fprintf('%f\t%f\t%f\t%f\n',a,b,c,fc);
if fa*fc< 0
b =c;
fb = eval(subs(y,x,b));
else
a =c;
fa = eval(subs(y,x,a));
end
c = (a*fb-b*fa)/(fb-fa);
fc = eval(subs(y,x,c));
end
fprintf('\nRoot is: %f\n', c);
end
OUTPUT:
Enter non-linear equations:
(x^2)-log(x)-12
Enter first guess: 3
Enter second guess: 4
PROGRAM_10: Solution of algebraic and transcendental equations by Newton-Raphson method.
Aim: Solve the algebraic and transcendental equations by Newton-Raphson Method.
Description: Newton- Raphson method:
The Newton-Raphson method (also known as Newton's method) is a way to quickly find a good approximation
for the root of a real-valued function f(x)=0. It uses the idea that a continuous and differentiable function can
be approximated by a straight-line tangent to it. Using the formula
f xn
xn 1 xn
f ' xn
Example 1: Write and execute MATLAB program to find the real root of the equation sinx + cosx + ex = 8
which lies between 2 and 3 using Newton Raphson method.
MATLAB code:
f = @(x) (sin(x) + cos(x) + exp(x) - 8 );
fd = @(x) (cos(x) - sin(x) + exp(x));
p0 = input('Enter initial approximation, p0:');
n = input('Enter no. of iterations, n:');
tol = input('Enter tolerance, tol: ');
i = 1;
while i <= n
d=f(p0)/fd(p0);
p0 = p0 - d;
if abs(d) < tol
fprintf('\nApproximate root of the given equation is x%d= %0.4f \n\n',n,p0);
break;
else
i = i+1;
end
End
OUTPUT:
Enter initial approximation, p0: 2
Enter no. of iterations, n: 20
Enter tolerance, tol: 0.0001
Approximate root of the given equation is x20= 2.0192
Example 2: Write and execute MATLAB program to find the real root of the equation xlog10x =1.2
which lies in (2, 3) using Newton Raphson method.
MATLAB code:
f = @(x) (x*log10(x)-1.2);
fd = @(x) (log10(x) + 0.4343);
p0 = input('Enter initial approximation, p0: ');
n = input('Enter no. of iterations, n: ');
tol = input('Enter tolerance, tol: ');
i = 1;
while i <= n
d=f(p0)/fd(p0);
p0 = p0 - d;
if abs(d) < tol
fprintf('\nApproximate root of the given equation is x%d= %0.4f \n\n',n,p0);
break;
else
i = i+1;
end
end
OUTPUT:
Enter initial approximation, p0: 3
Enter no. of iterations, n: 5
Enter tolerance, tol: 0.0001
Approximate root of the given equation is x5= 2.7406