Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Mac11 Matlab Manual

Uploaded by

hr260513
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Mac11 Matlab Manual

Uploaded by

hr260513
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

For Computer Science

Engineering Stream

MAC11

MATLAB
Manual for
CSE, ISE, CS(CS), CS(AIML),
AI&ML, AI&DS, BT

Department of Mathematics
Ramaiah Institute of Technology,
Bengaluru - 560054
Matlab Manual for MAC11

Introduction to MATLAB

When you start MATLAB, the desktop appears in its default layout.

Table 1: Basic Arithmetic Operations


Sl. Sl.
Input Output Input Output
No. No.
1 2+3 5 5 x^2 25
2 x=5; y=3; x+y 8 6 sqrt(y) 1.7321
3 x*y 15 7 x/0 Inf
4 x/y 1.6667 8 (x+y)/(x^2+y^2) 0.2353

Table 2: Basic Functions


Sl. Sl.
Input Output Input Output
No. No.
1 x=2; y=pi; 8 nthroot(-4,3) -1.5874
sin(y/4) 0.7071 Error: Error using
nthroot(-4,2) nthroot
asin(0.7071) 0.7854
2 9 If X is negative, N
Output will be displayed Syntax must be an odd
∎asin(x)=𝑠𝑖𝑛 −1 𝑥
in terms of radians nthroot(X,N) integer.
3 exp(x) 7.3891 10 z=sqrt(-4) 0.0000 + 2.0000i
4 log(x) 0.6931 11 imag(z) 2
5 z=log10(x) z=0.3010 12 real(z) 0
format long
6 z = 0.301029995663981 13 abs(z) 2
z
format short
7 11.5920 14 abs(-4) 4
cosh(y)
Note: If you end a statement with a semicolon, MATLAB performs the computation, but suppresses the
display of output in the Command Window.

Department of Mathematics, RIT


Matlab Manual for MAC11
Table 3: Basic Commands
Sl.
Command Output
No.
Clears all the text from the Command Window, resulting in a clear
1 clc
screen. (Does not delete the variables created)
Removes all variables from the current workspace, releasing them
2 clear
from system memory. (Does not clear the screen)
3 close all Closes all figures whose handles are visible
creates symbolic scalar variables
Example
Input Output
4 syms sin(x) Error: Unrecognized function
or variable 'x'.
syms x y sin(x)+exp(y)
sin(x)+exp(y)
Variable-precision arithmetic – evaluate each element of the
symbolic input x to at least d significant digits
Input Output
5 vpa a=((1 + a=5^(1/2)/2 + 1/2
sqrt(sym(5)))/2)
vpa(a) 1.6180339887498948482045868343656
vpa(a,3) 1.62
Performs algebraic simplification
Input Output
syms x cos(x)^2 + sin(x)^2
6 simplify
sin(x)^2+cos(x)^2
simplify(cos(x)^2 + 1
sin(x)^2)
Prints expression in a plain-text format that resembles typeset
mathematics.
Input Output
syms x y z=(y^2 + x^2)/(x*y)
7 pretty z=(y^2 + x^2)/(x*y)
pretty(z) 2 2
y +x
-------
xy
*For true typeset rendering, use Live Scripts instead
subs(s, old, new) returns a copy of s, replacing all occurrences
of old with new, and then evaluates s.
Input Output
8 subs syms x y 4+y
subs(x + y,x,4)
f(x,y) = x + y; b+a
f = subs(f,[x,y],[a,b])

Department of Mathematics, RIT


Matlab Manual for MAC11
input(prompt) displays the text in prompt and waits for the user
to input a value and press the Return key.
9 input
Input Output
x=input(“Enter the value of x:”) Enter the value of x: _
Formats data and displays the results on the screen
Input Output
a=1; a=1, b=1.450000, f=x + y
b=1.45;
f=x+y;
10 fprintf fprintf(“a=%d, b=%f,
f=%s”, a,b,f)
• To format numeric and character data use the following
%d – Integer %f – Floating-point %s – String
• To format the display use the following
\t – tab space \n – next line
Disp(x) displays the value of variable x without printing the
variable name
Input Output
11 disp
a=1 a=1
disp(a) 1
disp(“a is equal to ” + a) a is equal to 1
Differentiate the given function n times with respect to variable
var
Input Output
syms f(x)
f(x)=sin(x); cos(x)
diff(f)
12 diff(f,var,n)
syms f(x) cos(x)
f(x)=sin(x);
diff(f,x)
syms f(x) -sin(x)
f(x)=sin(x);
diff(f,x,2)
Evaluate the definite integral of the function f from a to b
Input Output
syms f(x)
f(x)=sin(x); -cos(x)
int(f)
13 int(f,var,a,b) syms f(x) log(tan(x/2))
f(x)=csc(x);
int(f,x) *csc(x)=cosec 𝑥
syms f(x) 1
f(x)=sin(x);
int(f,x,0,pi/2)

Department of Mathematics, RIT


Matlab Manual for MAC11
Table 4: Vectors and Matrices
Sl.
Input Output
No.
1 x=[1,2,3,4,5,6] x=1 2 3 4 5 6
2 x=1:1:6 x=1 2 3 4 5 6
3 x=1:6 x=1 2 3 4 5 6
4 x=linspace(1,6,5) x = 1.0000 2.2500 3.5000 4.7500 6.0000
5 y=x+1 y = 2.0000 3.2500 4.5000 5.7500 7.0000
6 y=x*2 y = 2.0000 4.5000 7.0000 9.5000 12.0000
a= 2 2 2 2 2
a=[1,2,3,2,1]
Error: Incorrect dimensions for matrix multiplication. Check that
the number of columns in the first matrix matches the number of
7 z=a*x
rows in the second matrix. To operate on each element of the
matrix individually, use TIMES (.*) for elementwise multiplication.
a and x are 1x5 matrices hence multiplication is not possible
z = 1.0000 4.5000 10.5000 9.5000 6.0000
8 z=a.*x ( .* represents elementwise multiplication, i.e., it will take
z = 1*1 2*2.25 3*3.5 2*4.75 1*6 )
9 y=x/2 y = 0.5000 1.1250 1.7500 2.3750 3.0000
Error: Matrix dimensions must agree.
10 y=2/x (The number 2 will be interpreted as a 1x1 matrix, making
regular division unfeasible. Use element-wise division instead.)
11 y=2./x y = 2.0000 0.8889 0.5714 0.4211 0.3333
12 y=a./x y = 1.0000 0.8889 0.8571 0.4211 0.1667
13 length(x) 6
1 2 3 1 3 5
14 M=[1 2 3;3 4 5;6 7 8] 3 4 5 15 N=[1 3 5;-1 4 6;-3 4 -2] -1 4 6
6 7 8 -3 4 -2
2 5 8 -10 23 11
16 M+N 2 8 11 17 M*N -16 45 29
3 11 6 -25 78 56
0 0 0 0
18 b=ones(1,3) 1 1 1 19 x=zeros(3,4) 0 0 0 0
0 0 0 0
Incorrect dimensions for matrix multiplication.
20 x*b x is a 3x4 matrix and b is a 1x3 matrix hence multiplication is
not possible
2 6 10
21 b*x 0 0 0 0 22 2*b.*N -2 8 12
-6 8 -4
22 size(x) 3 4 23 det(N) -52
0.6154 -0.5000 0.0385
24 inv(N) 0.3846 -0.2500 0.2115
-0.1538 0.2500 -0.1346

Department of Mathematics, RIT


Matlab Manual for MAC11
Working with Script file (.m file)
• Scripts consist of sets of MATLAB commands that are kept in basic text files.
• Script files must end with the extension '.m' (for example 'myScript.m'), and often these files
are referred to as m-files.
• Essentially, m-files run a sequence of MATLAB instructions. Alternatively, they can serve as
functions capable of receiving inputs, generating multiple outputs.

Working with Live Script file (.mlx file)


Live scripts and live functions are interactive documents that combine MATLAB code with formatted
text, equations, and images in a single environment called the Live Editor. In addition, live scripts
store and display output alongside the code that creates it.
To create a live script: MATLAB>Home>Live Script

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB01: Plotting Curves

Plotting XY Data

Syntax
plot(X,Y, 'options')
creates a 2-D line plot of the data in Y versus the corresponding values in X, where X and Y are
vectors of the same length.

Plotting function
fplot(f,xinterval)
plots expression or function f over the specified interval. Specify the interval as a two-element vector
of the form [xmin xmax].

If we did not mention xinterval, fplot plots the function f over the default interval [-5 5] for x

Example
Plot the functions 𝑦1 = 50 cos 𝑥 sin 𝑥 , 𝑦2 = 4𝑥 3 − 4𝑥 + 14, 𝑦3 = 10𝑥 in the range [−2,2]

Using plot
clc
clear
close

x = [-2:0.01:2];
%Define the functions to plot
y1 = 50*cos(x).*sin(x);
y2 = 4*x.^3-4*x+14;
y3 = 10*x;

plot(x,y1,'b','linewidth',1)
hold on
plot(x,y2,'--r','linewidth',1)
plot(x,y3,'-.m','linewidth',1.5)
hold off
%Customization (Optional)
xlabel('\bf x-Axis'); ylabel('\bf y-Axis')
title('\fontname{Arial} Cartesian Plot','fontsize',14)

legend('y1','y2','y3')

Output

Department of Mathematics, RIT


Matlab Manual for MAC11
Using fplot
clc
clear Output
close

syms x

y1 = 50*cos(x)*sin(x);
y2 = 4*x^3-4*x+14;
y3 = 10*x

fplot([y1,y2,y3],[-2,2])

%Customization (Optional)
xlabel('\bf x-Axis'); ylabel('\bf y-Axis')
title('Cartesian Plot','fontsize',14)

legend('y1','y2','y3')

Plotting Polar plot

Syntax
polarplot(theta,rho)
plots a line in polar coordinates, with theta indicating the angle in radians and rho indicating the radius
value for each point. The inputs must be vectors of equal length or matrices of equal size.

Example
Plot the graph of the polar curves 𝑟 = cos 2𝜃 ; 𝑟 = sin 3𝜃

clc Output
clear
close all

t=linspace(0,2*pi);

r1=input("Enter the first polar curve r1=f(t): r1=");


r2=input("Enter the second polar curve r2=f(t): r2=");

polarplot(t,r1,'m',t,r2,'b','linewidth',2);

Exercise:

Plot the graphs of the following functions:

a) 𝒚 = 𝐬𝐢𝐧 𝟐𝒙 + 𝐜𝐨𝐬 𝟐 𝒙 b) 𝒚 = 𝒙𝟑 + 𝐜𝐨𝐬 𝟑𝒙 + 𝒕𝒂𝒏𝟑 𝒙

Hint: Input for 𝒙𝟑 : x.^3, 𝐭𝐚𝐧𝟑 𝒙: (tan(x)).^3

Plot the following polar curve:


𝒂𝜽 𝒂
a) 𝒓𝟑 = 𝟖 𝐜𝐨𝐬 𝟑𝜽 & 𝒓𝟑 = 𝟖 𝐬𝐢𝐧 𝟑𝜽 b) 𝒓 = & 𝒓=
𝟏+𝜽 𝟏+𝜽𝟐

𝒂𝜽 𝟑
Hint: Input for : 2*t./(1+t), 𝒓𝟑 = 𝟖 𝐜𝐨𝐬 𝟑𝜽 ⇒ 𝒓 = √𝟖 𝐜𝐨𝐬 𝟑𝜽: nthroot(8*cos(3*t),3)
𝟏+𝜽

Department of Mathematics, RIT


Matlab Manual for MAC11
LAB 02:
i) Angle between radius vector and tangent vector
ii) Angle of intersection between two polar curves
i) Angle between radius vector and tangent vector

Algorithm:
𝑟′
• For a given curve 𝑟 = 𝑓(𝜃), find 𝜙 = cot −1 ( ), where 𝑟 ′ = 𝑑𝑟/𝑑𝜃
𝑟

clear
clc
close
syms theta
%Get the curve
r1=input("Enter the first curve r1(theta): r1=");
%Find phi1
phi1=simplify(acot(diff(r1)/r1));
%display phi1
fprintf("\n Angle between radius vector and tangent vector to the curve %s:\n phi=
%s",r1,phi1)

Output

Enter the first curve r1(theta): r1=2*(1+cos(theta))


Angle between radius vector and tangent vector to the curve 2*cos(theta) + 2:
phi1= -acot(sin(theta)/(cos(theta) + 1))

ii) Angle of intersection between two polar curves

Algorithm:
𝑟′
• For a given curve 𝑟1 = 𝑓1(𝜃), 𝑟2 = 𝑓2(𝜃), find 𝜙1 and 𝜙2 using 𝜙 = cot −1 ( ), where 𝑟 ′ = 𝑑𝑟/𝑑𝜃
𝑟
• Solve given curves for 𝜃 value
• Get the required appropriate 𝜃 value from the solution
• Find |𝜙2 − 𝜙1| by substituting obtained 𝜃 value

clear
clc
close
syms theta

%Get the two curves


r1=input("Enter the first curve r1(theta): r1=");
r2=input("Enter the second curve r2(theta): r2=");
%Find phi1 and phi2

phi1=simplify(acot(diff(r1)/r1));
phi2=simplify(acot(diff(r2)/r2));

%display phi1 and phi2


fprintf("\n Angle between radius vector and tangent vector to the curve %s:\n phi1=
%s",r1,phi1)
fprintf("\n Angle between radius vector and tangent vector to the curve %s:\n phi2=
%s",r2,phi2)

%Find t(point of intersection)


Department of Mathematics, RIT
Matlab Manual for MAC11
fprintf('\n The values of theta at the point of intersection are: ')
S=solve(r1==r2,theta,'Real',true)

%Get the theta


tt=input("\n Choose the value of theta: ");

%Calculate the angle between the given curves


ang1= abs(vpa(subs(phi1-phi2, {theta},{tt})));
ang2=vpa(pi-ang1);
fprintf('\n Angle between given polar curves = %f or %f \n', ang1, ang2);

Output
Enter the first curve r1(theta): r1=2*(1+cos(theta))
Enter the second curve r2(theta): r2=2*(1-cos(theta))
Angle between radius vector and tangent vector to the curve 2*cos(theta) + 2:
phi1= -acot(sin(theta)/(cos(theta) + 1))
Angle between radius vector and tangent vector to the curve 2 - 2*cos(theta):
phi2= -acot(sin(theta)/(cos(theta) - 1))
The values of theta at the point of intersection are: S =
pi/2
Choose the value of theta: pi/2
Angle between given polar curves = 1.570796 or 1.570796

Exercise:

Find the angle of intersection between following pair of curves:


𝒂
a) 𝒓 = 𝒂 𝐜𝐨𝐬 𝜽 and 𝒓 = 𝒃 𝐬𝐢𝐧 𝜽 b) 𝒓 = 𝒂(𝟏 + 𝒔𝒊𝒏𝜽) and 𝒓 = 𝒃(𝟏 − 𝒔𝒊𝒏𝜽) c) 𝒓 = 𝒂 𝐥𝐨𝐠 𝜽 and 𝒓 =
𝐥𝐨𝐠 𝜽

𝒂
Hint: Input for 𝒓 = : 2/((log(theta)))
𝐥𝐨𝐠 𝜽

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 03: Partial differentiation and Jacobian

Syntax

diff(f,var,n)
computes the nth derivative of f with respect to var.

Example1
𝑥
𝜕𝑈
Find all the first order and second order partial derivatives of the function 𝑈 = 𝑒 𝑦 . Also, find at x=2,
𝜕𝑥
𝜕𝑈 𝜕𝑈
at y=2 and at x=2 & y=3.
𝜕𝑥 𝜕𝑦

clear
clc
syms x y

%Define U
U(x,y)=exp(x/y);
%First derivatives
Ux=diff(U,x);
Uy=diff(U,y);
%Second derivatives
Uxx=simplify(diff(Ux,x));
Uyy=simplify(diff(Uy,y));
Uxy=simplify(diff(Ux,y));
Uyx=simplify(diff(Uy,x));

fprintf('The first order partial derivatives are \n Ux = %s \n Uy = %s \n',Ux, Uy);


fprintf('\n The second order partial derivatives are \n Uxx = %s \n Uyy = %s\n Uxy = %s \n Uyx
= %s \n',Uxx,Uyy,Uxy,Uyx);

U1=Ux(2,y);
U2=Ux(x,2);
U3=Uy(2,3);

fprintf('\n Ux(2,y)=%s; \t Ux(x,2)=%s; \t Uy(2,3)=%f \n',U1,U2,U3)

Output
The first order partial derivatives are
Ux = exp(x/y)/y
Uy = -(x*exp(x/y))/y^2

The second order partial derivatives are


Uxx = exp(x/y)/y^2
Uyy = (x*exp(x/y)*(x + 2*y))/y^4
Uxy = -(exp(x/y)*(x + y))/y^3
Uyx = -(exp(x/y)*(x + y))/y^3

Ux(2,y)=exp(2/y)/y; Ux(x,2)=exp(x/2)/2; Uy(2,3)=-0.432830

Example 2
1 z z
If z = then prove that x −y = y2 z3 .
y − 2 xy + 1
2 x y

Department of Mathematics, RIT


Matlab Manual for MAC11
clear all
clc
syms z x y
z=(1-2*x*y+y^2)^(-1/2);
zx=diff(z,x);
zy=diff(z,y);
LHS=simplify(x*zx-y*zy)
RHS=simplify(y^2*z^3)
if(LHS==RHS)
fprintf('\n The given condition is satisfied\n');

else
fprintf('\n The given condition is not satisfied')
end

Output
LHS =
y^2/(- 2*x*y + y^2 + 1)^(3/2)
RHS =
y^2/(- 2*x*y + y^2 + 1)^(3/2)
The given condition is satisfied

Jacobian

jacobian([u1,u2,…],[x1,x2,…])
computes the Jacobian of a vector function which is a matrix of the partial derivatives of that function

• To find the determinant find the determinant of the resultant Jacobian matrix.

Example 1

v = x+ y (u, v)
If u = x − 2 y and
2
then find the Jacobian . Also, find the value of Jacobian at (1, 0).
 ( x, y )
clear all
clc
syms x y u v
u(x,y)=input('Enter u(x,y):');
v(x,y)=input('Enter v(x,y):');
J(x,y)=simplify(det(jacobian([u,v],[x,y])));
fprintf('\n J((u,v)/(x,y))= %s \n', J);

p=input('\n Enter the point in the form [a,b] : ');


val=J(p(1),p(2));
fprintf('\n J((u,v)/(x,y)) at (%d,%d) is %d \n', p(1),p(2), val)

Output
Enter u(x,y):x^2-2*y
Enter v(x,y):x+y
J((u,v)/(x,y))= 2*x + 2
Enter the point in the form [a,b] : [1,0]
J((u,v)/(x,y)) at (1,0) is 4

Example 2
(u, v)
If u = x2 − y2 and v = 2 xy where x = r cos t , y = r sin t then find the Jacobian . Also, show
 ( x, y )
(u, v ) (u, v )
that = 4r 3 and hence find the value of Jacobian at (3,1).
(r , t ) (r , t )

Department of Mathematics, RIT


Matlab Manual for MAC11
clear all
clc
syms x y u v r t
u(x,y)=input('Enter u(x,y):');
v(x,y)=input('Enter v(x,y):');
J1(x,y)=det(jacobian([u(x,y),v(x,y)],[x,y]));
fprintf('\n J((u,v)/(x,y))= %s \n', J1);

x=input('\n Enter x(r,t):');


y=input('Enter y(r,t):');
J2(r,t)=simplify(det(jacobian([u(x,y),v(x,y)],[r,t])));
fprintf('\n J((u,v)/(r,t))=%s \n', J2)

p=input('\n Enter the point in the form [a,b] : ');


val=J2(p(1),p(2));
fprintf('\n J((u,v)/(r,t)) at (%d,%d) is %d \n', p(1),p(2), val)

Output
Enter u(x,y):x^2-y^2
Enter v(x,y):2*x*y

J((u,v)/(x,y))= 4*x^2 + 4*y^2

Enter x(r,t):r*cos(t)
Enter y(r,t):r*sin(t)

J((u,v)/(r,t))=4*r^3

Enter the point in the form [a,b] : [3,1]


J((u,v)/(r,t)) at (3,1) is 108

Example 3
(u, v, w)
If u = x sin y cos z , v = x sin y sin z and w = x cos y then find the Jacobian .
( x, y, z )

clear all
clc
syms x y z u v w
u(x,y,z)=input('Enter u(x,y,z):');
v(x,y,z)=input('Enter v(x,y,z):');
w(x,y,z)=input('Enter w(x,y,z):');
J(x,y,z)=simplify(det(jacobian([u,v,w],[x,y,z])));
fprintf('\n J((u,v,w)/(x,y,z))= %s \n', J);

Output
Enter u(x,y,z):x*sin(y)*cos(z)
Enter v(x,y,z):x*sin(y)*sin(z)
Enter w(x,y,z):x*cos(y)
J((u,v,w)/(x,y,z))= x^2*sin(y)

Department of Mathematics, RIT


Matlab Manual for MAC11
Exercise:

y z u u u
a) If u= + the show that x + y +z =0
z x x y z

1 1 log x − log y f f
b) If f = + + then prove that x + y + 2 f = 0.
x 2
xy x +y
2 2
x y

x3 + y3 u u 5
c) If u= then prove that x +y = u.
x+ y x y 2

(u, v, w)
d) If u = x + 3 y 2 − z 2 , v = 4 x 2 yz, w = 2 z 2 − xy then evaluate at (1,-1,0).
 ( x, y , z )

( x, y)
e) If x = e v sec u and y = e v tan u then find the Jacobian
(u, v)

(u, v )
f) If u = x 2 − 2y 2 and v = 2 x 2 − y 2 where x = r cos , y = r sin  then show that = 6r 3 sin 2 .
(r , )

(u, v, w)
g) If u = yz v = zx , w = xy and x = r cos  sin  , y = r sin  sin  , z = r cos  then find .
(r ,  , )

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 04: Vector Calculus

Gradient, Divergence, Curl, Laplacian

Syntax
returns the gradient vector of symbolic scalar field f with respect to
g = gradient(f,v) vector v in Cartesian coordinates.

returns the divergence of symbolic vector field V with respect to


d = divergence(V,X) vector X in Cartesian coordinates. Vectors V and X must have the
same length.
returns the curl of symbolic vector field V with respect to vector X in
c = curl(V,X) three-dimensional Cartesian coordinates. Both the vector field V and
the vector X must be vectors with three components.
returns the Laplacian of the symbolic field f with respect to the vector
l = laplacian(f,v) v in Cartesian coordinates. If f is an array, then the function
computes the Laplacian for each element of f and returns the output l
that is the same size as f.

Example 1
Find gradient of a given scalar function 𝑓 = 2𝑦𝑧𝑠𝑖𝑛(𝑥) + 3𝑥𝑠𝑖𝑛(𝑧)cos(𝑦) at (1,2,3)

clear
clc
syms x y z
f(x,y,z) =input("Enter the function f(x,y,z):");
gradf=(simplify(gradient(f,[x y z])));
fprintf("grad(f)=%s\n",gradf)
p=input('\n Enter the point in the form [a,b,c] : ');
val=vpa(gradf(p(1),p(2),p(3)));
fprintf('\n grad(f) at (%d,%d,%d) is (%.4f)i + (%.4f)j + (%.4f)k
\n',p(1),p(2),p(3),val(1),val(2),val(3))

Output
Enter the function f(x,y,z):2*y*z*sin(x) + 3*x*sin(z)*cos(y)
grad(f)=[3*cos(y)*sin(z) + 2*y*z*cos(x); 2*z*sin(x) - 3*x*sin(y)*sin(z); 2*y*sin(x) +
3*x*cos(y)*cos(z)]
Enter the point in the form [a,b,c] : [1,2,3]
grad(f) at (1,2,3) is (6.3074)i + (4.6639)j + (4.6018)k

Example 2
Find the divergence of the given vector field 𝑓 = 𝑥𝑦𝑖 + 2𝑥𝑦 2 + 3𝑥𝑧 3 𝑘 at (3,4,5).

clear all
clc
syms x y z
F =input('Enter the components of vector F in [x y z] form : ');
div(x,y,z)=divergence(F,[x y z]);
fprintf('\n div(F) = %s \n',div);
p=input('\n Enter the point in the form [a,b,c] : ');
val=div(p(1),p(2),p(3));
fprintf('\n div(F) at (%d,%d,%d) is %d \n',p(1),p(2),p(3),val);

Department of Mathematics, RIT


Matlab Manual for MAC11
Output
Enter the components of vector F in [x y z] form : [x*y 2*x*y^2 3*x*z^3]
div(F) = y + 4*x*y + 9*x*z^2
Enter the point in the form [a,b,c] : [3,4,5]
div(F) at (3,4,5) is 727

Example 3
Find the gradient of the scalar function 𝑓 = −(sin(𝑥) + sin(𝑦))2 and interpret geometrically

clear all
clc
syms x y
f = input("Enter the function f(x,y):");
gradf = gradient(f,[x y])
[X1, Y1] = meshgrid(-1:.1:1,-1:.1:1);
G1 = subs(gradf(1),[x y],{X1,Y1});
G2 = subs(gradf(2),[x y],{X1,Y1});
quiver(X1,Y1,G1,G2)

Output

Enter the function f(x,y):-(sin(x) +


sin(y))^2

gradf =

-2*cos(x)*(sin(x) + sin(y))
-2*cos(y)*(sin(x) + sin(y))

Example 4
Find the gradient of the scalar function 𝑓 = 𝑥𝑦 2 + 𝑦𝑧 2 + 𝑧𝑥 2 and interpret geometrically.

clear all
clc
syms x y z
f = input("Enter the function f(x,y,z):");
gradf = gradient(f,[x y z])
[X1, Y1, Z1] = meshgrid(-1:.2:1,-1:.2:1,-1:.2:1);
G1 = subs(gradf(1),[x y z],{X1,Y1,Z1});
G2 = subs(gradf(2),[x y z],{X1,Y1,Z1});
G3 = subs(gradf(3),[x y z],{X1,Y1,Z1});
quiver3(X1,Y1,Z1,G1,G2,G3)
xlabel('X')
ylabel('Y')
zlabel('Z')

Output

Enter the function


f(x,y,z):x*y^2+y*z^2+z*x^2

gradf =

2*x*z + y^2
2*x*y + z^2
x^2 + 2*y*z

Department of Mathematics, RIT


Matlab Manual for MAC11
Example 5
Find the Laplacian of the scalar function 𝑥 3 + 𝑦 2 − 𝑙𝑜𝑔𝑧

clear
clc
syms x y z
f(x,y,z) =input("Enter the scalar function f(x,y,z):");
L=(simplify(laplacian(f,[x y z])));
fprintf("Laplacian of f(x,y,z) is %s \n",L)

Output
Enter the scalar function f(x,y,z):x^3 + y^2 - log(z)
Laplacian of f(x,y,z) is 6*x + 1/z^2 + 2

Example 6
To find directional derivative of function 𝑥𝑦 2 + 𝑦𝑧 2 + 𝑧𝑥 2 in the direction of the vector 𝑖 + 𝑗 + 𝑘 at (1,2,3)

clear all
clc
syms x y z
f= input("Enter the function f(x,y,z):");
gradf = gradient(f, [x y z])
n=input('\nEnter the components of directional vector as [x y z]:');
m = n/norm(n);
D(x,y,z) = simplify(dot(gradf',m));
fprintf('\nDirectional derivative is %s\n', D)
p=input('\nEnter the point as [a,b,c]:');
val=vpa(D(p(1),p(2),p(3)));
fprintf('Directional derivative at (%d,%d,%d) is %f\n', p(1),p(2),p(3),val)

Output
Enter the function f(x,y,z):x^2*z + x*y^2 + y*z^2
gradf =
2*x*z + y^2
2*x*y + z^2
x^2 + 2*y*z
Enter the components of directional vector as [x y z]:[1 1 1]
Directional derivative is (3^(1/2)*(x + y + z)^2)/3
Enter the point as [a,b,c]:[1,2,3]
Directional derivative at (1,2,3) is 20.784610

Exercise:

1. Find gradient of a given scalar function 𝒇 = 𝒙𝒚𝒛 + 𝟑𝒚𝒔𝒊𝒏(𝒛)𝐜𝐨𝐬(𝒚) at the point (1,2,3).

2. Find the divergence of the given vector field 𝒇 = 𝒙𝒊 + 𝟐𝒚𝟐 + 𝟑𝒛𝟑 𝒌.

3. Find div𝑭 ̂.
⃗ at the point (2,3,4) where ⃗𝑭 = (𝒚𝟐 + 𝒛𝟐 − 𝒙𝟐 )𝒊̂ + (𝒛𝟐 + 𝒙𝟐 − 𝒚𝟐 )𝒋̂ + (𝒙𝟐 + 𝒚𝟐 − 𝒛𝟐 )𝒌

4. Find the gradient of the scalar function 𝒇 = 𝒙𝟐 − 𝒚𝟐 and interpret geometrically.

5. Find the Laplacian of the scalar function 𝒙𝟐 − 𝒚𝟐 + 𝟒𝒛.

6. To find directional derivative of function 𝒙𝒄𝒐𝒔𝒚 + 𝒙𝒚𝒛𝟐 + 𝒚𝒛𝒄𝒐𝒔𝒙in the direction of the vector 𝒙𝒚𝒊̂ +
̂.
𝒙𝒚𝒛𝒋̂ + 𝒚𝒛𝒌

7. Find the directional derivative of  = 𝒙𝟐 − 𝟐𝒙𝒚 + 𝒛𝟑 at the point (1,−2,−1) along the vector 𝟐𝒊̂ − 𝟒𝒋̂ + 𝟒𝒌
̂.

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 05: Double Integrals

Plotting the region

clear
clc
% Region of integration
xL=input("Enter lower limit of x")
xU=input("Enter Upper limit of x")
x = linspace(xL, xU); % x limits
yL=input("Enter lower limit of y")
yU=input("Enter Upper limit of y")
Li = yU >= yL ; % Logical Vector
figure
plot(x,yU,x,yL)
hold on
patch([x(Li) fliplr(x(Li))], [yU(Li) fliplr(yL(Li))], 'b')
hold off
grid

Example:

With the program to mark the region of integration in the following double integrals:
2 2x 4 x
1)  0 x2
f ( x, y ) dy dx   f ( x, y) dy dx
2) 1 2
Output Output
Enter lower limit of x: 0 Enter lower limit of x: 1
Enter Upper limit of x: 2 Enter Upper limit of x: 4
Enter lower limit of y: x.^2 Enter lower limit of y: 2+0.*x
Enter Upper limit of y: 2.*x Enter Upper limit of y: sqrt(x)

NOTE: i) If ‘y’ lower limit is constant, give input as yL.*x.

ii) For the polar plot patch won't work (instead of that we need to use polyfill but it is not
user-friendly).

Exercise:

2 4− x 2  sin x 42 x 2 3− y

a)  
0 2− x
f ( x, y ) dy dx b) 
0 0
f ( x, y ) dy dx c) 
0 x 2
f ( x, y ) dy dx d)   f ( x, y) dy dx
0 y
4 4

Department of Mathematics, RIT


Matlab Manual for MAC11
Double Integral

Syntax Remark Syntax Remark


f,xL,xU,yL, yU f,xL,xU,yL,yU are
must be function need not be function
integral2(f,xL,xU,yL,yU) handlers, i.e., int(int(f,y,yL,yU),x,xL,xU) handlers, i.e., no
use @(x,y), need to use @(x,y),
@(x), @(y) @(x), @(y)

clear
clc
syms x y
f = matlabFunction(input("Enter the integrand: "));
disp('f(x,y) :');
disp(f);

xL=input("Enter lower limit of x: ");


xU=input("Enter Upper limit of x: ");
yL=input("Enter lower limit of y: ");
yU=input("Enter Upper limit of y: ");

d = integral2(f,xL,xU,yL,yU);
disp("Double Integral of f(x,y) :");
disp(d);

Write a program to evaluate double integral.

2 3
a) ∫1 ∫2 (𝑥 − 1/𝑦)2 𝑑𝑥𝑑𝑦 b)
1
∫0 ∫𝑥 𝑥𝑦 𝑑𝑦𝑑𝑥
√𝑥

Output: Output:
Enter the integrand: (x-1/y)^2 Enter the integrand: x*y
f(x,y) : f(x,y) :
@(x,y) (x-1./y).^2 @(x,y)x.*y
Enter lower limit of x: 1 Enter lower limit of x: 0
Enter Upper limit of x: 2 Enter Upper limit of x: 1
Enter lower limit of y: 2 Enter lower limit of y: @(x) x
Enter Upper limit of y: 3 Enter Upper limit of y: @(x) sqrt(x)
Double Integral of f(x,y) : 1.2836 Double Integral of f(x,y) :
0.0417

Exercise:
a
a a− x2 3 x2 +a2
x
  a − x − y dy dx  
2 2 2
a) (ans:0.5236) b) dy dx (ans:0.1215)
0 0 0 0 x + y2 + a2
2

𝟐𝝅 𝝅 𝟐𝝅 𝒙
c) ∫𝝅 ∫𝟎 𝒚 𝒔𝒊𝒏𝒙 + 𝒙 𝒄𝒐𝒔𝒚 𝒅𝒙𝒅𝒚 (ans:9.8696) d) ∫𝝅 ∫𝟎 𝒚 𝒔𝒊𝒏𝒙 + 𝒙 𝒄𝒐𝒔𝒚 𝒅𝒙𝒅𝒚 (ans:32.0988)

NOTE: matlabFunction which converts the variable expression into to function handler, if the
integrand is a constant function then don’t use this converter. Just use

f = input("Enter the integrand: ");

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 06: Triple Integrals

Triple Integral

clear
clc
syms x y z
f = matlabFunction(input("Enter the integrand f(x,y,z) : "));
disp('f(x,y,z) :');
disp(f);

xL=input("Enter lower limit of x: ");


xU=input("Enter Upper limit of x: ");
yL=input("Enter lower limit of y: ");
yU=input("Enter Upper limit of y: ");
zL=input("Enter lower limit of z: ");
zU=input("Enter Upper limit of z: ");

d = integral3(f,xL,xU,yL,yU,zL,zU);
disp("Triple Integral of f(x,y,z) :");
disp(d);

Write a program to evaluate Triple integral.


1 x x+ y

   (xyz )dx dy dz
1 2 2

 e
2 x+ y+ z
a) b) dz dy dx
0 0 1 0 0 0

OUTPUT: OUTPUT:
Enter the integrand f(x,y,z): x*y*z^2 Enter the integrand f(x,y,z): exp(x+y+z)
f(x,y,z) : f(x,y,z) :
@(x,y,z)x.*y.*z.^2 @(x,y,z)exp(x+y+z)
Enter lower limit of x: 0 Enter lower limit of x: 0
Enter Upper limit of x: 1 Enter Upper limit of x: 1
Enter lower limit of y: 0 Enter lower limit of y: 0
Enter Upper limit of y: 2 Enter Upper limit of y: @(x) x
Enter lower limit of z: 1 Enter lower limit of z: 0
Enter Upper limit of z: 2 Enter Upper limit of z: @(x,y) x+y
Triple Integral of f(x,y,z) : 2.3333 Triple Integral of f(x,y,z) : 3.6263

Exercise:

1 1 y e log y e x 1 1− x 2 1− x 2 − y 2

a)    xyz dz dx dy
0 0 0
b)    log z dz dx dy
1 1 1
c)  
0 0

0
xyz dx dy dz

Ans: 0.0625 Ans: 2.7593 Ans: 0.0208

NOTE: Use @(x,y) if the limit is a function of two variable, @(x) for function of one variable

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 07: Line Integrals

Line integral Main program


▪ Because the line integral needs to be computed repeatedly, it is Call function1
advisable to encapsulate it within a function.
To create a function End of the main program
• The function should begin as follows:
%Define the function1
function [y1, ..., yN] = fun_name(x1, ..., xM)
• This declares a function named fun_name that accepts inputs x1, function f=function1(x,y)
..., xM and returns outputs y1, ..., yN. The function should end
{
with end.
• Function definition should be at the end of the main program. }
• To use the function, call it from the main main program as many
times as needed. end

%%%%%%%%%%%%%%%% Main Program %%%%%%%%%%%%%%%%%%


clc
clear
syms x y
LInt=0;
%Get the number of sub path in the curve C
n=input("How many subcurves are ther in the curve C? :")
%Calculate the line integral along each path
for i=1:n
line(i)=LineIntegral(x,y);
LInt =vpa(LInt +line(i))
end
%%%%%%%%%%%%%%%% Main Program ends %%%%%%%%%%%%%%%%%%
%Define function for Line integral
function line = LineIntegral(x,y)
option=input("1: y=f(x)\n2: x=g(y)\n")

switch option
case 1
y=input("Enter the function f(x): \n")
r=[x y];
F=input("Enter the vector function F(x,y)=[F1 F2]: F(x,y)")
dr=diff(r,x);
integrand1=dot(F,dr);
xL=input("Enter the lower limit of x:");
xU=input("Enter the Upper limit of x:");
line=int(integrand1,x,xL,xU)
case 2
x=input("Enter the function g(y): \n")
r=[x y];
F=input("Enter the vector function F(x,y)=[F1 F2]: F(x,y)")
dr=diff(r,y);
integrand1=dot(F,dr);
yL=input("Enter the lower limit of y:");
yU=input("Enter the Upper limit of y:");
line=int(integrand1,y,yL,yU)
otherwise
fprintf("Give the proper input")
end

end
%%%%%%%%%%%%%%%% Line Integral definition ends %%%%%%%%%%%%%%%%%%

Department of Mathematics, RIT


Matlab Manual for MAC11
Example 1
Evaluate ∫𝑐 𝐹 ⋅ 𝑑𝑟, where 𝑐 is the curve in plane 𝑦 = 2𝑥 2 from (0,0) to (1,2) and 𝐹 = 3𝑥𝑦 𝑖̂ − 𝑦 2 𝑗̂.

How many subcurves are ther in the curve C? :1


n = 1
1: y=f(x)
2: x=g(y)
1
option = 1
Enter the function f(x):
2*x^2
y =
2*x^2
Enter the vector function F(x,y)=[F1 F2]: F(x,y)=[3*x*y -y^2]
F =
[6*x^3, -4*x^4]
Enter the lower limit of x:0
Enter the Upper limit of x:1
line =
-7/6
LInt =
-1.1666666666666666666666666666667

Line integral using parametric form

clear
clc
syms x y z t
x=input("Enter x(t):"); % If x ,y, z is a function of ‘t’
y=input("Enter y(t):");
z=input("Enter z(t):");

r=[x y z];
F=input("Enter the vector function F(x,y,z):")
dr=diff(r,t);
integrand1=dot(F,dr);
tl=input("Enter the lower limit of t:");
tu=input("Enter the Upper limit of t:");
line=int(integrand1,t,tl,tu)

Example 1
Evaluate ∫𝑐 𝐹 ⋅ 𝑑𝑟, where 𝑐 is the curve given by 𝑥 = 2𝑡 2 , 𝑦 = 𝑡, 𝑧 = 𝑡 3 from (0,0,0) to (2,1,1) and 𝐹 =
(2𝑦 + 3)𝑖̂ + 𝑥𝑧𝑗̂ + (𝑦𝑧 − 𝑥)𝑘̂.

Output
Enter x(t):2*t^2
Enter y(t):t
Enter z(t):t^3
Enter the vector function F(x,y,z):[2*y+3 x*z yz-x]
Enter the vector function F(x,y,z):[2*y+3 x*z y*z-x]
F =
[3 + 2*t, 2*t^5, - 2*t^2 + t^4]
Enter the Lower limit of t:0
Enter the Upper limit of t:1
line =
288/35

Department of Mathematics, RIT


Matlab Manual for MAC11

Exercise:
  
1. If F = xy iˆ + yz ˆj + zx kˆ evaluate  F . dr where c is the curve represented by
c

x = t, y = t , z = t , − 1  t  1 .
2 3

 
2. Find the circulation of F round the curve c , where F = (x − y ) iˆ + (x + y ) ˆj and c is the circle
x2 + y2 = 4 , z = 0 .

3. Find the total work done by a force F = 2 xy iˆ − 4 z ˆj + 5 x kˆ along the curve

x = t , y = 2t + 1, z = t
2 3
from t= 0 to t = 1 .
  
4. Evaluate  F . dr , where F = cos y iˆ − x sin y ˆj and c is the curve y = 1 − x 2 in xy -plane from
c
(1, 0) to (0, 1).

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 08: Green’s Theorem

Greens theorem

𝑀(𝑥, 𝑦), 𝑁(𝑥, 𝑦) be continuous in a region 𝑅 of 𝑥𝑦 plane bounded by a closed curve 𝑐 then
𝜕𝑁 𝜕𝑀
∮ 𝑀𝑑𝑥 + 𝑁𝑑𝑦 = ∫ ∫ − 𝑑𝑥𝑑𝑦
𝑐 𝑅 𝜕𝑥 𝜕𝑦

Algorithm

• Create a function for LHS: Evaluate ∮𝑐 𝑀𝑑𝑥 + 𝑁𝑑𝑦 along the curve 𝑐 using Line integral
𝜕𝑁 𝜕𝑀
• Create a function for RHS: Evaluate ∫ ∫𝑅 − 𝑑𝑥𝑑𝑦 using multiple integrals
𝜕𝑥 𝜕𝑦
• Check whether LHS=RHS or not

%%%%%%%%%%%%%%%% Main Program %%%%%%%%%%%%%%%%%%


clc
clear

syms x y

LHS=0;
%Get the number of sub path in the curve C
n=input("How many sub curves are ther in the curve C? :")
%Calculate the line integral along each path (LHS)
for i=1:n
line(i)=LineIntegral(x,y);
LHS=vpa(LHS+line(i))
end
%Calculate the double integral (RHS)
RHS=vpa(MultiIntegral(x,y))

%%%%%%%%%%%%%%%% Main Program ends %%%%%%%%%%%%%%%%%%


%Define function for Line integral
function line = LineIntegral(x,y)
option=input("1: y=f(x)\n2: x=g(y)\n")

switch option
case 1
y=input("Enter the function f(x): \n")
r=[x y];
F=input("Enter the vector function F(x,y)=[F1 F2]: F(x,y)=")
dr=diff(r,x);
integrand1=dot(F,dr);
xL=input("Enter the lower limit of x:");
xU=input("Enter the Upper limit of x:");
line=int(integrand1,x,xL,xU)
case 2
x=input("Enter the function g(y): \n")
r=[x y];
F=input("Enter the vector function F(x,y)=[F1 F2]: F(x,y)=")
dr=diff(r,y);
integrand1=dot(F,dr);
yL=input("Enter the lower limit of y:");
yU=input("Enter the Upper limit of y:");
line=int(integrand1,y,yL,yU)
otherwise
fprintf("Give the proper input")

Department of Mathematics, RIT


Matlab Manual for MAC11
end

end

%%%%%%%%%%%%%%%% Line Integral definition ends %%%%%%%%%%%%%%%%%%


%Define function for Double integral
function d = MultiIntegral(x,y)

M= input("Enter the M(x,y): ");


N= input("Enter the N(x,y): ");
f=diff(N,x)-diff(M,y);

disp('f(x,y) :');
disp(f);

xL=input("Enter lower limit of x: ");


xU=input("Enter Upper limit of x: ");
yL=input("Enter lower limit of y: ");
yU=input("Enter Upper limit of y: ");

d = int(int(f,y,yL,yU),x,xL,xU);
end
%%%%%%%%%%%%%%%% Double Integral definition ends %%%%%%%%%%%%%%%%%%

Example 1

Verify Green’s theorem for  ( y − sin x)dx + cos y dy


c
where c is the plane triangle enclosed by the line

 2x
y = 0, x = , y= .
2 

Output
How many subcurves are ther in the curve C? :3
n =
3
1: y=f(x)
2: x=g(y)
1
option =
1
Enter the function f(x):
0
y =
0
Enter the vector function F(x,y)=[F1 F2]: F(x,y)=[y-sin(x) cos(y)]
F =
[-sin(x), 1]
Enter the lower limit of x:0
Enter the Upper limit of x:pi/2
line =
-1

LHS =
-1.0

1: y=f(x)
2: x=g(y)
2
option =

Department of Mathematics, RIT


Matlab Manual for MAC11
2
Enter the function g(y):
pi/2
x =
1.5708
Enter the vector function F(x,y)=[F1 F2]: F(x,y)=[y-sin(x) cos(y)]
F =
[- 1 + y, cos(y)]
Enter the lower limit of y:0
Enter the Upper limit of y:1
line =
sin(1)

LHS =
-0.1585290151921034933474976783697

1: y=f(x)
2: x=g(y)
1
option =
1
Enter the function f(x):
2*x/pi
y =
(2*x)/pi
Enter the vector function F(x,y)=[F1 F2]: F(x,y)=[y-sin(x) cos(y)]
F =
[(2*x)/pi - sin(x), cos((2*x)/pi)]
Enter the lower limit of x:pi/2
Enter the Upper limit of x:0
line =
1 - sin(1) - pi/4

LHS =
-0.78539816339744830961566084581988

Enter the M(x,y): y-sin(x)


Enter the N(x,y): cos(y)
f(x,y) :
-1

Enter lower limit of x: 0


Enter Upper limit of x: pi/2
Enter lower limit of y: 0
Enter Upper limit of y: 2*x/pi

RHS =

-0.78539816339744830961566084581988

Exercise:

1. Verify Green’s theorem for ∫𝒄(𝟑𝒙𝟐 − 𝟖𝒚𝟐 )𝒅𝒙 + (𝟒𝒚 − 𝟔𝒙𝒚)𝒅𝒚 where c is the plane triangle enclosed by the
line 𝒙 = 𝟎, 𝒚 = 𝟎, 𝒙 + 𝒚 = 𝟏.

2. . Verify Green’s theorem for ∫𝒄(𝒙𝟐 − 𝒚𝟐 )𝒅𝒙 + 𝟐𝒙𝒚𝒅𝒚 where c is the rectangle bounded by rectangle 𝒚 =
𝟎, 𝒙 = 𝟎, 𝒚 = 𝒃 and 𝒙 = 𝒂.

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 09: Modular Arithmetic- Diophantine Equation

Remainder function – (mod)


mod function is used to find the remainder when one number is divided by another. If R is the
remainder obtained when X is divided by Y then R=mod(X,Y)

Syntax of the mod function:


R = mod (X, Y)

Example 1: ‘mod’ function for scalar inputs


Code Output
R = mod (15, 6) R =
3

Solving linear Diophantine equation


The simplest linear Diophantine equation takes the form 𝑎𝑥 + 𝑏𝑦 = 𝑐, where a, b and c are given
integers. The solutions are described by the following theorem:
This Diophantine equation has a solution (where x and y are integers) if and only if c is a multiple of the
greatest common divisor of a and b. Moreover, if (𝑥, 𝑦) is a solution, then the other solutions have the
form (𝑥 + 𝑘𝑣, 𝑦 − 𝑘𝑢), where k is an arbitrary integer, and u and v are the quotients of a and b
(respectively) by the greatest common divisor of a and b.
Let 𝑎𝑥 + 𝑏𝑦 = 0, 𝑥, 𝑦 ∈ 𝑍 be a homogeneous linear Diophantine equation. If 𝑔𝑐𝑑(𝑎, 𝑏) = 𝑑, then the complete
𝑏 𝑎
family of solutions to the above equation is 𝑥 = 𝑘, and 𝑦 = − 𝑘, 𝑘 ∈ 𝑍.
𝑑 𝑑

To find the particular solution of the Diophantine equation:


clc
clear;
syms x y t
assume([x y], 'integer') % assume ‘x’ and ‘y’ are integers
eqn = 50*x +20*y == 300 ; % declare the equation
disp(eqn)
c = coeffs(lhs(eqn) ,[y,x]); %c(1)->Coefficient of x, c(2)->Coefficient of y
r=rem(rhs(eqn),gcd(c(1),c(2)));
if r~=0
disp('No Solution')
else
fprintf('%d is multiple of gcd(%d,%d)=%d, hence it has
solution\n',rhs(eqn),c(1),c(2),gcd(c(1),c(2)))
if rhs(eqn)~=0
[xSol, ySol] = solve(eqn,[x y]); % solve for ;x’ and ‘y’
xComp=xSol+t*(c(2)/gcd(c(1),c(2)));
yComp=ySol+t*(-c(1)/gcd(c(1),c(2)));
else
xSol=c(2)/gcd(c(1),c(2));
ySol=-c(1)/gcd(c(1),c(2));
xComp=xSol*t;
yComp=ySol*t;

Department of Mathematics, RIT


Matlab Manual for MAC11
end
fprintf(' Solution is : x=%d, y=%d\n',xSol,ySol)

fprintf('General Solution [x,y]:\n')


fprintf('x=')
disp(xComp)
fprintf('y=')
disp(yComp)
end

Output
50*x + 20*y == 300
300 is multiple of gcd(50,20)=10, hence it has solution
Solution is : x=-30, y=90
General Solution [x,y]:
x=2*t - 30
y=90 - 5*t

Exercise:

1. Find the particular solution of the following linear Diophantine Equations:

a) 6x+9y=0 b) 2x+4y=21 c) 20x+16y=500

2. Find all the solutions (x, y) to the Diophantine equation 11x + 13y = 369 for which x and y are both
positive.

Department of Mathematics, RIT


Matlab Manual for MAC11

LAB 10: Euclid’s Algorithm & Linear Congruences

GCD of two numbers 𝒎, 𝒏 using Euclid’s algorithm

clc
clear;
prompt1 = "Enter the first number: ";
m = input(prompt1); %Get the first number
prompt2 = "Enter the second number: ";
n = input(prompt2); %Get the first number
ans=euclid(m,n); %Call the recursive function euclid
if ans==-1
fprintf('Enter the numeric values\n')
elseif ans==-2
fprintf('Enter the integral values\n')
elseif ans==-3
fprintf('Enter the positive values\n')
else
fprintf('%d\n',ans)
end

function [res] = euclid(m,n)


% Are m and n the right types?
if ~isnumeric(m) || ~isnumeric(n)
res = -1;
return
end
% Are m and n integer-like?
if m ~= int64(m) || n ~= int64(n)
res = -2;
return;
end
% Are m and n greater than zero?
if m <= 0 || n <= 0
res = -3;
return
end
% Swap m and n if m less than n
% to allow the algorithm to function properly
if m < n
tmp = m;
m = n;
n = tmp;
end
% Result of modulus is zero so we have found the gcd
if mod(m,n) == 0
fprintf('GCD(%d,%d)=>',m,n);
res = n;
else
fprintf('GCD(%d,%d)=>',m,n);
res = euclid(n,mod(m,n)); % Euclid's algorithm
end

end

Department of Mathematics, RIT


Matlab Manual for MAC11
Output
Enter the first number: 18
Enter the second number: 480
GCD(480,18)=>GCD(18,12)=>GCD(12,6)=>6

Exercise

Find GCD of the following: 𝟏) (𝟐𝟒, 𝟑𝟎), 𝟐) (𝟏𝟐𝟖, 𝟗𝟔)

Solution of a linear congruence 𝒂𝒙 ≡ 𝒄(𝒎𝒐𝒅 𝒎)


clc
clear;
prompt1 = "To solve Linear Congruence ax =c(mod m)\n Enter a: ";
a = input(prompt1);
prompt2 = "Enter c: ";
c = input(prompt2);
prompt3 = "Enter m: ";
m = input(prompt3);

[g,u0,v0] = EuclidMatrix(m,a);
if ( mod(c,g) ) ~= 0
disp('No solutions.')
solutions = [];
return
end

disp([ num2str(m) 'x + ' num2str(a) 'y = ' num2str(g) ])


disp(['Number of Solutions: (' num2str(u0) ')' num2str(m)...
' + (' num2str(v0) ')' num2str(a) ' = ' num2str(g) ]);

u = u0 - (a / g);
v = v0 + (m / g);
x = v * (c / g);
y = u * (c / g);
S = @(k) x + k * (m/g);
solutions = mod(S(0:g-1),m);
fprintf('solution=%f\n',solutions)

% Euclidean Algorithm, Beazout's Coefficients are stored in matrix


function [g,u,v] = EuclidMatrix(a,b)
M = [ 1 0; 0 1 ];
n = 0;
while (b ~= 0)
q = floor(a/b);
M = M * [ q 1; 1 0];
t = a;
a = b;
b = t - q * b;
n = n + 1;
end
g = a;
u = ( -1 )^n * M(2,2);
v = (-1)^(n+1) * M(1,2);
disp([ num2str(u) 'x + ' num2str(v) 'y = ' num2str(g) ])
end

Department of Mathematics, RIT


Matlab Manual for MAC11
Output
To solve Linear Congruence ax =c(mod m)
Enter a: 15
Enter c: 6
Enter m: 7
-2x + 1y = 1
7x + 15y = 1
Number of Solutions: (-2)7 + (1)15 = 1
solution=6.000000

Exercise:

Solve the following congruences

1) 𝟐𝒙 ≡ 𝟓𝟏(𝒎𝒐𝒅 𝟖) 2) 𝟒𝒙 ≡ 𝟐𝟔(𝒎𝒐𝒅 𝟕) 3) 𝟐𝟓𝒙 ≡ 𝟏𝟓(𝒎𝒐𝒅 𝟐𝟗)

4) 𝟗𝒙 ≡ 𝟒𝟐(𝒎𝒐𝒅 𝟔) 5) 𝟔𝒙 ≡ 𝟏𝟓(𝒎𝒐𝒅 𝟐𝟏)

Department of Mathematics, RIT

You might also like