Showing posts with label equation. Show all posts
Showing posts with label equation. Show all posts

Monday 10 July 2023

CFD Basics: Code Vectorization

     This post is about comparing 2 codes to solve the 2D Laplace equation using finite difference method. A sample code mentioned under "Code 01" uses nested loops. We must, wherever possible avoid nested loops. The solution to the code is shown in Fig. 1. The second code uses vectorization instead of the nested loops. The vectorized version is mentioned under  "Code 02".

Code 01

clear
clc
close all
%% Parameters
Lx = 1; % Length of the domain in the x-direction
Ly = 1; % Length of the domain in the y-direction
Nx = 201; % Number of grid points in the x-direction
Ny = 201; % Number of grid points in the y-direction
dx = Lx / (Nx - 1); % Grid spacing in the x-direction
dy = Ly / (Ny - 1); % Grid spacing in the y-direction
%% Initialize temperature matrix
T = zeros(Nx, Ny);
T(:, 1) = 100;
T(:, Nx) = 0;
T(1, :) = 25;
T(Ny, :) = 50;
%% Gauss-Seidel iteration
max_iter = 50000; % Maximum number of iterations
tolerance = 1e-10; % Convergence tolerance
error = inf; % Initialize error
iter = 0; % Iteration counter
while error > tolerance && iter < max_iter
T_old = T;
% Solve Laplace equation using Gauss-Seidel iterations
for i = 2:Nx-1
for j = 2:Ny-1
T(i, j) = ((T(i+1, j) + T(i-1, j))*dy^2 + (T(i, j+1) + T(i, j-1))*dx^2) / (2*(dx^2 + dy^2));
end
end
% Compute error
error = max(abs(T(:) - T_old(:)));
% Increment iteration counter
iter = iter + 1;
end
%% plotting
[X, Y] = meshgrid(0:dx:Lx, 0:dy:Ly);
contourf(X, Y, T')
axis equal
colormap jet
colorbar
clim([0 100])
title('Temperature Distribution Non Vec')
xlabel('x')
ylabel('y')
zlabel('Temperature (T)')
colorbar

Code 02

clear
clc
close all
%% Parameters
Lx = 1; % Length of the domain in the x-direction
Ly = 1; % Length of the domain in the y-direction
Nx = 201; % Number of grid points in the x-direction
Ny = 201; % Number of grid points in the y-direction
dx = Lx / (Nx - 1); % Grid spacing in the x-direction
dy = Ly / (Ny - 1); % Grid spacing in the y-direction
i = 2:Nx-1;
j = 2:Ny-1;
%% Initialize temperature matrix
T = zeros(Nx, Ny);
T(:, 1) = 100;
T(:, Nx) = 0;
T(1, :) = 25;
T(Ny, :) = 50;
%% Gauss-Seidel iteration
max_iter = 50000; % Maximum number of iterations
tolerance = 1e-10; % Convergence tolerance
error = inf; % Initialize error
iter = 0; % Iteration counter
while error > tolerance && iter < max_iter
T_old = T;
% Solve Laplace equation using Gauss-Seidel iterations
T(i, j) = ((T(i+1, j) + T(i-1, j))*dy^2 + (T(i, j+1) + T(i, j-1))*dx^2) / (2*(dx^2 + dy^2));
% Compute error
error = max(abs(T(:) - T_old(:)));
% Increment iteration counter
iter = iter + 1;
end
%% plotting
[X, Y] = meshgrid(0:dx:Lx, 0:dy:Ly);
contourf(X, Y, T')
axis equal
colormap jet
colorbar
clim([0 100])
title('Temperature Distribution Vec')
xlabel('x')
ylabel('y')
zlabel('Temperature (T)')
colorbar

Result

Results say that vectorized code is ~1.5x faster than nested looped code for 200x200 matrix. Simulation results are now presented.

Fig. 1, Vectorized VS Nested Loops


Thank you for reading! I hope you learned something new! If you like this blog and want to hire me as your PhD student, please get in touch!

Sunday 24 April 2022

1D Laplace's equation using Finite Difference Method

This post is about FDM for Laplace Equation with various boundary conditions.

MATLAB Code (1D, Dirichlet Boundary Conditions)

%% initialize the workspace, clear the command window


clear; clc


%% finite difference 1D laplace dirichlet boundary conditions %% d2u/dx2 = 0 %% u(o) = 10, u(L) = 4 %% Ax=b%%


N = 4 ; %number of grid points

L = 1; %length of domain

dx = L/(N-1); %element size


%% initialize variables %%


l = linspace(0,L,N); %independent

u=zeros(1,N); %dependent


%% boundary conditions %%


u(1)=10;

u(end)=4;


%% b vector %%


b=zeros(N-2,1);

b(1) = b(1) - u(1);

b(end) = b(end) - u(end);


%% A matrix


A = -2*eye(N-2,N-2);

for i=1:N-2

    if i<N-2

        A(i,i+1)=1;

    end

    if i>1

        A(i,i-1)=1;

    end

end


%% solve for unknowns %%


x = A\b;


%% fill the u vector with unknowns %%


u(2:end-1) = x;


%% plot the results %%


hold on; grid on; box on, grid minor

set(gca,'FontSize',40)

set(gca, 'FontName', 'Times New Roman')

ylabel('u','FontSize',44)

xlabel('l','FontSize',44)


plot(l,u,'-o','color',[0 0 0],'LineWidth',2,'MarkerSize',20)


MATLAB Code (1D, Mixed Boundary Conditions)

%% initialize the workspace, clear the command window

clear; clc

%% finite difference 1D laplace mixed boundary conditions %% d2u/dx2 = 0 %% u(o) = 10, du/dx(L) = 4 %% Ax=b%%

N = 5; %number of grid points
L = 1; %length of domain
dx = L/(N-1); %element size
a = 4;
%% initialize variables %%

l = linspace(0,L,N); %independent
u=zeros(1,N); %dependent

%% dirichlet boundary condition %%

u(1) = 10;

%% b vector %%

b=zeros(N-1,1);
b(1) = b(1) - u(1);
b(end) = b(end) + dx*a; %neumann boundary condition added to b vector

%% A matrix

A = -2*eye(N-1,N-1);
for i=1:N-1
    if i<N-1
        A(i,i+1)=1;
    end
    if i>1
        A(i,i-1)=1;
    end
end
A(N-1,N-1) = -1; %neumann boundary condition added to A matrix
%% solve for unknowns %%

x = A\b;

% fill the u vector with unknowns %%

u(2:end) = x;

%% plot the results %%

hold on; grid on; box on, grid minor
set(gca,'FontSize',40)
set(gca, 'FontName', 'Times New Roman')
ylabel('u','FontSize',44)
xlabel('l','FontSize',44)

plot(l,u','-o','color',[0 0 0],'LineWidth',2,'MarkerSize',20)

Friday 9 March 2018

Solve PDEs using MATLAB (Code)

This is a post about a code I wrote to solve  1-D Poisson's equations. The method employed is called the finite difference method. For 1-D Laplace equation, the RHS of the equation mentioned below goes to zero. Hence all the terms in the B(i) loop equal zero. Also, B(1) and B(Nx) terms equal to the boundary conditions only. I hope this code helps you in learning something.

The example equation is mentioned below.
d2y/dx2 = x2+1 and y(0)=10, y(1)=20

The result of the code is a plot between the dependent and the independent variables, as shown in Fig. 1. The accuracy of the solutions lie around 1.5 % of the analytical solution.

%solution to 1D Poisson's equations with dirichlet boundary conditions, 2nd order accurate, uniform grid
clear; clc;
Nx=101; %Enter the number of grid points
clc;
A=zeros(Nx,Nx); %Stiffness matrix
B=zeros(Nx,1); %Dependent variable vector, also used for boundary conditions and other known terms
x=zeros(Nx,1); %Independent variable vector
x(Nx)=1; %Domain size
dx=x(Nx)/(Nx-1); %Grid spacing
B(1)=(((x(1).^2)+1)*(dx.^2))-10; %Enter the function the PDE equals to multiplied by the square of the grid spacing minus the first boundary condition
B(Nx)=(((x(Nx).^2)+1)*(dx.^2))-20; %Enter the function the PDE equals to multiplied by the square of the grid spacing minus the second boundary condition
for i=2:Nx-1 %Off boundary values for the dependent variable vector
    B(i)=((x(i).^2)+1)*(dx.^2); %Enter the function the PDE equals to multiplied by the the square of the grid spacing
end
for i=1:Nx-1 %Loop for independent variable
    x(i+1)=(i)*dx;
end
for i=1:Nx %Diagonal terms for the stiffness matrix
    A(i,i)=-2;
end
for i=1:Nx-1 %Off diagonal terms for the stiffness matrix
    A(i,i+1)=1;
    A(i+1,i)=1;
end
X=A\B;
hold on
set(gca,'FontSize',28)
xlabel('Independent Variable','FontSize',38.5)
ylabel('Dependent Variable','FontSize',38.5)
title('Dependent VS Independent Variable (d^2y/dx^2 = x^2+1)','FontSize',38.5);
plot(x,X)


Fig. 1. Plot from the code

Wednesday 21 February 2018

Solve ODEs using MATLAB (Code)

I have decided to teach myself some CFD coding using my own intuition and some free online tutorials. This is a post about code I wrote to solve a first order ordinary differential equation. The method employed is called the finite difference method. I will start by coding equations using this method and will slowly move to finite volume method. I hope this code helps you in learning something.

The equation in question is mentioned below.
dy/dx = x+4 and y(0)=3

A uniform grid was employed, as I have not yet figured out how to make non uniform grid. When I figure it out, I will update it here, which will be soon.

The code, mentioned below, starts with a variable called Nx, which represents the total number of grid points in which the domain is divided in to. A rule of thumb, the more points in the domain, more accurate the solution becomes at the cost of computation resources, mainly CPU time and RAM and storage.

x and y are the vectors in which the known and the unknown values are stored. x has the known values, like the length of a pipe through which a fluid flow or a rod through which heat flows etc. y stores the unknown values like temperature of the rod or velocity of the fluid etc. The values are stored at nodes.

y(1) means first value in the vector y. which also happens to be our boundary condition. y is the value of the function at x=0. x=0 is the first value in in the x vector, written as x(1).

x(Nx-1) represents the domain size. Minimum domain size is usually zero e.g. starting point of a rod or a pipe and maximum can be any real number.

To calculate the grid spacing, represented by dx, the domain size was divided by the number of elements. In this example, we have four nodes, two at corners and two in-between, forming a total of three elements.

First order finite difference method was used to discretize the given equation. And a for loop was used for the solution. Using 4 grid points, the solution has an accuracy of 2.22% against the analytical solution of the equation which can be verified by hand calculations. Thank you for reading.

%solution to dy/dx=x+4 y(0)=3
%uniform grid
clear; clc;
Nx=4; %number of grid points
x=zeros(Nx,1); %x vector, known, goes from some known value to maximum value of the domain
y=zeros(Nx,1); %y vector, one value known due to boundary condition rest unknown
y(1)=3; %boundary condition
x(Nx-1)=1; %domain size
dx=x(Nx-1)/(Nx-1); %grid spacing
for i=1:Nx-1
    x(i+1)=(i)*dx;
    y(i+1)=(dx.*(x(i)+4))+y(i); %discretized differential equation
end