PKK
Printing String
……………………..
.MODEL SMALL
.STACK 100H
.DATA
STRING DB 'My name is Md. Mehedi', '$'
.CODE
MAIN PROC FAR
MOV AX,@DATA
MOV DS,AX
; load address of the string
LEA DX,STRING
;output the string
;loaded in dx
MOV AH,09H
INT 21H
;interrupt to exit
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
Upper to Lower Case
………………………………..
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
MOV AH,1 ;INPUT
INT 21H
MOV BL,AL
ADD BL,20H ;Upper to Lower
MOV AH,2
MOV DL,BL
INT 21H
EXIT:
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
Bisection
ORG 100H
.MODEL SMALL
.STACK 100H
.DATA
R DB 'ENTER RANGE: $'
F DB 0
S DB 1
SUM DB ?
N DW ?
FAB DB 13, 10, 13, 10, '**FIBONACCI SERIES**$'
.CODE
MAIN PROC
MOV DX, OFFSET R
MOV AH, 9
INT 21H
MOV N, 0
MOV BL, 10
INPUT:
MOV AH, 1
INT 21H
CMP AL, 13
JE NEXT
SUB AL, 30H
MOV AH, 0
MOV CX, AX
MOV AX, N
MUL BL
ADD AX, CX
MOV N, AX
JMP INPUT
NEXT:
LEA DX, FAB
MOV AH, 9
INT 21H
MOV CX, N
L:
PUSH CX
MOV DL, 10
MOV AH, 2
INT 21H
MOV DL, 13
MOV AH, 2
INT 21H
MOV BL, F
ADD BL, S
MOV SUM, BL
MOV AH, 0
MOV AL, SUM
MOV DX, 0
MOV BX, 10
MOV CX, 0
L1:
DIV BX
PUSH DX
MOV DX, 0
MOV AH, 0
INC CX
CMP AX, 0
JNE L1
MOV AH, 2
L2:
POP DX
ADD DX, 48
INT 21H
LOOP L2
MOV BL, S
MOV F, BL
MOV BL, SUM
MOV S, BL
POP CX
LOOP L
RET
MAIN ENDP
Euler
% Prompt the user to input initial values and step size
xo = input("Enter the value of xo: ");
yo = input("Enter the value of yo: ");
h = input("Enter the value of h: ");
% Prompt the user to input the function as a string
func_str = input("Enter the function in terms of x and y: ", 's');
% Convert the function string to a function handle
f = str2func(['@(x,y)', func_str]);
% Prompt the user to input the number of iterations
n = (yo-xo)/h;
% Implement Euler's Method
for i = 1:n
y = yo + h * f(xo, yo);
fprintf('y%i = %f\n', i, y);
yo = y;
xo = xo + h;
end
False position
%function = @(argument)(expression)
f =input ('Enter the EXP: ');
%Get user input for initial value/intervals
a=input('Enter the lower bound, a: ');
b=input('Enter the upper bound, b: ');
%check if there is a root in the interval
while f(a)*f(b)>=0
fprintf('There is no root in the given interval.\n');
a=input('Enter the lower bound, a: ');
b=input('Enter the upper bound, b: ');
end
acc=input('Enter the values of accuracy: ');
iteration= 0;
matched_roots = 0;
while abs(b-a)>acc
c=(a*f(b) - b*f(a)) / (f(b) - f(a));
fc = f(c);
%plot the interval
x_interval = [a,b];
y_interval = [f(a), f(b)];
plot(x_interval, y_interval, 'b-o');
hold on;
%plot root
plot(c, fc, 'ro', 'MarkerSize', 8);
%check if the root is matched twice
if f(a)*fc<=0
b=c;
else
a=c;
end
iteration = iteration+1;
fprintf('Iteration %d: Interval[%f, %f], Root = %f\n', iteration,a,b,c);
%check if the root matched twice
if abs(f(c))<acc
matched_roots = 0;
end
%break if the root is matched twice
if matched_roots>=2
break;
end
end
fprintf('The root of the equation according to the false Position Method is: %f\n',c);
Fixed Point
% fixedpointfun
function xr = FixedPointIteartion(fun,x0)
pmin = 0; % x limits of the plot. Change for different functions if needed.
pmax = 1;
% First plot g(x) and y=x to see the behaviour
figure
hold on
fplot(@(x) fun(x),[pmin,pmax],'LineWidth',2)
fplot(@(x) x,[pmin,pmax],'LineWidth',2)
fplot(0,[pmin,pmax],'-k')
ylim([0,1]) % y limits of the plot. Change for different functions if needed.
xlabel('x')
ylabel('g(x)')
title('Fixed-Point Iteration Demo')
grid on
% Initialize variables
es = 0.001;
maxit = 100;
% prepare the output header
fprintf('\n # xi er\n');
count = 0; % iteration counter
er = 1; % initial error value to enter loop
xi = x0; % initialize xi and xold
xold = xi;
fxold = fun(xold); % will be used for plotting
fprintf('%3g %10.6g %10.4g\n',count,xi,er);
plot([xold,xold],[xold,fxold],'--k'); % allows us to visualize the approximations
erplot = zeros(1,50);
% main loop
while (abs(er) > es && count<maxit)
count = count +1;
xold = xi; % keep the previous estimate
fxold = fun(xold); % will be used for plotting
xi = fun(xi); % calculate the new estimate
fxi = fun(xi);
plot([xold,xi,xi],[fxold,xi,fxi],'--k'); % allows us to visualize the approximations
er = (xi-xold)/xi; % relative error
erplot(count) = er;
fprintf('%3g %10.6g %10.4g\n',count,xi,er);
% pause % Wait for key press
end
if count >= maxit
disp(' ')
disp(['Failed to converge in ',num2str(maxit),' iterations'])
disp(' ')
disp('--------------------------------------------')
disp(' ')
xr = NaN;
else
disp(' ')
disp(['Root has been found at x = ',num2str(xi)])
disp(' ')
disp('--------------------------------------------')
disp(' ')
xr = xi;
end
figure
hold on
fplot(0,[0,count],'-k')
plot(erplot(1:count),'LineWidth',2)
title('Relative Error')
xlabel('Iteration Number')
ylabel('Relative Error (er)')
hold off
end
% use it command line "FixedPointIteartion(@(x)cos(x),0.1)"
% use it command line "FixedPointIteartion(@(x)(cos(x)+3)/2,0.1)"
Gauss Elimination
function x = gausselimination(A,b)
[rA,cA] = size(A); % Determine the size of A
[rb,cb] = size(b); % Determine the size of b
% Input checks
if rA ~= cA
disp('Error: A is not a square matrix')
return
else
n = rA;
end
if cb ~= 1
disp('Error: b is not a column vector')
return
end
if cA ~= rb
disp('Error: Matrix and vector dimensions are not compatible')
return
end
dA = det(A);
if dA == 0
disp('Error: Matrix is singular')
return
end
% Initialize the result x
x = zeros(rA,1); % initialize x as a column vector
% Step 1: Form the combined matrix [A b]
a = [A b];
disp(' ')
disp('Combined Matrix [A|b]')
disp('-----------------------------')
disp(a)
disp(' ')
% Step 2: Forward elimination
disp('-----------------------------')
disp('Forward Elimination')
disp('-----------------------------')
disp(' ')
for k = 1:n
disp(['Pivot Row ',num2str(k)])
disp('-----------------------------')
for i = k+1:n
m = a(i,k)/a(k,k);
for j = k:n+1
a(i,j)=a(i,j)-m*a(k,j); % eliminate elements in the rows below
end
end
disp(a)
disp(' ')
end
disp('-----------------------------')
disp('Obtain the Result')
disp('-----------------------------')
disp(' ')
% Back substitution
x(n) = a(n,n+1)/a(n,n);
for i = n-1:-1:1
sum = a(i,n+1);
for j = i+1:n
sum = sum - a(i,j)*x(j);
end
x(i) = sum/a(i,i);
end
disp(x)
end
Example-
% defines matrix A
A = [1, 1, 1;
2, 3,-1;
1, 3, 2];
% defines vector b
b = [ 2;
9;
5];
x = gausselimination(A,b)
Gauss Jacobi
function x = gaussjacobi(A,b,x0)
[rA,cA] = size(A); % Determine the size of A
[rb,cb] = size(b); % Determine the size of b
% Input checks
if rA ~= cA
disp('Error: A is not a square matrix')
return
else
n = rA;
end
if cb ~= 1
disp('Error: b is not a column vector')
return
end
if cA ~= rb
disp('Error: Matrix and vector dimensions are not compatible')
return
end
dA = det(A);
if dA == 0
disp('Error: Matrix is singular')
return
end
% Initialize the variables
maxit = 100;
es = 0.0001;
er = 1;
xnew = x0;
count = 0;
% Prepare R and D-inverse matrices
R = A;
Dinv = zeros(n);
for i=1:n
R(i,i)=0;
Dinv(i,i)=1/A(i,i);
end
% For display only
outmat = zeros(1,n+2);
outmat(1,:) = [count transpose(xnew) er];
% main loop
while(er>es && count<maxit)
count = count + 1; % Increment the counter
xold = xnew; % keep the old estimate
xnew = Dinv*(b - R*xold); % update the new estimate
er = norm(xnew-xold)/norm(xnew); % approximate relative error
outmat =[outmat; count transpose(xnew) er]; % For display
end
% Display the results
if count<maxit
disp('Gauss-Jacobi Method')
disp('-------------------------------------------------')
disp('Output format:')
disp('First column = iteration number')
disp('Next columns = estimates of the components of x')
disp('Last column = er')
disp(' ')
disp(outmat);
disp(' ');
x = xnew;
disp(['In ',num2str(count),' iterations, x was found to be: '])
disp(x);
disp(' ');
else
disp(['Failed to converge in ',num2str(count),' iterations'])
x = NAN;
end
Example-
A= [26 2 2;3 27 1;2 3 17];
b= [12.6;-14.3;6.0];
x0= [0;0;0];
gaussjacobi(A,b,x0);
Gauss Jordan
function x = gaussjordan(A,b)
[rA,cA] = size(A); % Determine the size of A
[rb,cb] = size(b); % Determine the size of b
% Input checks
if rA ~= cA
disp('Error: A is not a square matrix')
return
else
n = rA;
end
if cb ~= 1
disp('Error: b is not a column vector')
return
end
if cA ~= rb
disp('Error: Matrix and vector dimensions are not compatible')
return
end
dA = det(A);
if dA == 0
disp('Error: Matrix is singular')
return
end
% Initialize the result x
x = zeros(rA,1); % initialize x as a col
% Step 1: Form the combined matrix [A b]
a = [A b];
disp(' ')
disp('Combined Matrix [A|b]')
disp('-----------------------------')
disp(a)
disp(' ')
% Step 2: Forward elimination
disp('-----------------------------')
disp('Forward Elimination')
disp('-----------------------------')
disp(' ')
for k = 1:n
disp(['Pivot Row ',num2str(k)])
disp('-----------------------------')
a(k,:) = a(k,:)/a(k,k); % normalize the pivot row
for i = k+1:n
m = a(i,k)/a(k,k);
for j = k:n+1
a(i,j)=a(i,j)-m*a(k,j); % eliminate elements in the rows below
end
end
for i = 1:k-1
m = a(i,k)/a(k,k);
for j = k:n+1
a(i,j)=a(i,j)-m*a(k,j); % eliminate elements in the rows above
end
end
disp(a)
disp(' ')
end
disp('-----------------------------')
disp('Obtain the Result')
disp('-----------------------------')
disp(' ')
x = a(:,n+1); % obtain x directly as the right hand column
disp(x)
end
Example-
% defines matrix A
A = [1, 1, 1;
2, 3,-1;
1, 3, 2];
% defines vector b
b = [ 2;
9;
5];
x = gaussjordan(A,b)
Gauss Seidel
function x = gaussseidel(A,b,x0)
[rA,cA] = size(A); % Determine the size of A
[rb,cb] = size(b); % Determine the size of b
% Input checks
if rA ~= cA
disp('Error: A is not a square matrix')
return
else
n = rA;
end
if cb ~= 1
disp('Error: b is not a column vector')
return
end
if cA ~= rb
disp('Error: Matrix and vector dimensions are not compatible')
return
end
dA = det(A);
if dA == 0
disp('Error: Matrix is singular')
return
end
% Initialize the variables
maxit = 100;
es = 0.0001;
er = 1;
xnew = x0;
count = 0;
% Prepare U and L matrices
U = zeros(n);
for i=1:n
for j = i+1:n
U(i,j)=A(i,j);
end
end
L = A - U;
% For display only
outmat = zeros(1,n+2);
outmat(1,:) = [count transpose(xnew) er];
% main loop
while(er>es && count<maxit)
count = count + 1; % increment the counter
xold = xnew; % keep the old estimate
% Calculate the new estimate by forward substitution
xnew(1) = (b(1) - U(1,:)*xnew)/L(1,1);
for i = 2:n
sum = 0;
for j = 1:i-1
sum = sum + L(i,j)*xnew(j);
end
xnew(i) = (b(i)-U(i,:)*xnew-sum)/L(i,i);
end
er = norm(xnew-xold)/norm(xnew); % absolute relative error
outmat =[outmat; count transpose(xnew) er]; % for display
end
% Display the results
if count<maxit
disp('Gauss-Seidel Method')
disp('-------------------------------------------------')
disp('Output format:')
disp('First column = iteration number')
disp('Next columns = estimates of the components of x')
disp('Last column = er')
disp(' ')
disp(outmat);
disp(' ');
x = xnew;
disp(['In ',num2str(count),' iterations, x was found to be: '])
disp(x);
fprintf('\n er = ');
fprintf('%10.6g\n\n',er);
else
disp(['Failed to converge in ',num2str(count),' iterations'])
x = 'NAN';
end
Example =
A= [26 2 2;3 27 1;2 3 17];
b= [12.6;-14.3;6.0];
x0= [0;0;0];
gaussseidel(A,b,x0);
Newton Rapson Method
% NewtonRaphsonMethod
function xr = NewtonRaphsonMethod(fun, dfun, x0)
% Set limits for the plot
pmin = 0;
pmax = 3;
% Plot the function and y=x to visualize behavior
figure
hold on
fplot(@(x) fun(x), [pmin, pmax], 'LineWidth', 2)
fplot(@(x) x, [pmin, pmax], 'LineWidth', 2)
fplot(0, [pmin, pmax], '-k')
xlabel('x')
ylabel('f(x)')
title('Newton-Raphson Method Demo')
grid on
% Initialize variables
es = 0.001;
maxit = 100;
% Print output header
fprintf('\n # xi er\n');
count = 0; % Iteration counter
er = 1; % Initial error value
xi = x0; % Initial guess
erplot = zeros (1,50);
fprintf('%3g %10.6g %10.4g\n', count, xi, er);
% Main loop
while (abs(er) > es && count < maxit)
count = count + 1;
xold = xi; % Keep the previous estimate
fxold = fun(xold);
% Calculate the new estimate using Newton-Raphson formula
xi = xold - fun(xold) / dfun(xold);
plot([xold, xi], [fxold, 0], '--k'); % Visualize the approximation
er = (xi - xold) / xi; % Relative error
erplot (count) = er;
fprintf('%3g %10.6g %10.4g\n', count, xi, er);
end
if count >= maxit
disp(' ')
disp(['Failed to converge in ', num2str(maxit), ' iterations'])
disp(' ')
disp('--------------------------------------------')
disp(' ')
xr = NaN;
else
disp(' ')
disp(['Root has been found at x = ', num2str(xi)])
disp(' ')
disp('--------------------------------------------')
disp(' ')
xr = xi;
end
% Plot the relative error versus iteration number
figure
hold on
fplot(0, [0, count], '-k')
plot(erplot(1:count),'LineWidth',2)
title('Relative Error')
xlabel('Iteration Number')
ylabel('Relative Error (er)')
hold off
end
Example:
% Define your trigonometric function and its derivative
fun = @(x) x*sin(x)+cos(x);
dfun = @(x) x*cos(x);
% Initial guess
x0 = 1;
% Call the NewtonRaphsonMethod function with your function, its derivative, and initial guess
root = NewtonRaphsonMethod(fun, dfun, x0);
% Define your trigonometric function and its derivative
fun = @(x) sin(x) - x/2;
dfun = @(x) cos(x) - 0.5;
% Initial guess
x0 = 1;
% Call the NewtonRaphsonMethod function with your function, its derivative, and initial guess
root = NewtonRaphsonMethod(fun, dfun, x0);
% Define your function and its derivative
fun = @(x) x^3 - 2*x - 5;
dfun = @(x) 3*x^2 - 2;
% Initial guess
x0 = 2;
% Call the NewtonRaphsonMethod function with your function, its derivative, and initial guess
root = NewtonRaphsonMethod(fun, dfun, x0);
Runge Kutta
% Prompt the user to input initial values and step size
xo = input("Enter the value of xo: ");
yo = input("Enter the value of yo: ");
h = input("Enter the value of h: ");
% Prompt the user to input the function as a string
func_str = input("Enter the function in terms of x and y: ", 's');
% Convert the function string to a function handle
f = str2func(['@(x,y)', func_str]);
% Prompt the user to input the number of iterations
n = (yo-xo)/h;
% Implement Runge-Kutta Method (4th Order)
for i = 1:n
k1 = h * f(xo, yo);
k2 = h * f(xo + h/2, yo + k1/2);
k3 = h * f(xo + h/2, yo + k2/2);
k4 = h * f(xo + h, yo + k3);
y = yo + (k1 + 2*k2 + 2*k3 + k4)/6;
fprintf('y%i = %f\n', i, y);
yo = y;
xo = xo + h;
end
Comments
Post a Comment