set up coefficient matrix and rhs vector for a 2d unsteady heat conduction equation in matlab

To set up coefficient matrix and rhs vector for a 2d unsteady heat conduction equation in Matlab, we can use the Finite Difference Method (FDM). The FDM is a numerical method for approximating the solutions of differential equations using finite differences to approximate derivatives.

Let's consider the following equation:

equation

where T is the temperature distribution, α is the thermal diffusivity, and S(x,y,t) is the source term.

We can approximate the second derivatives of T using centered differences as follows:

equation

equation

where Δx and Δy are the grid spacings in the x and y directions, respectively.

We can discretize the equation in time using the Backward Euler method as follows:

![equation](https://latex.codecogs.com/svg.image?\frac{T_{i,j}^{n} - T_{i,j}^{n-1}}{\Delta&space;t}&space;=&space;\alpha\left(\frac{T_{i-1,j}^n&space;-&space;2T_{i,j}^n&space;+&space;T_{i+1,j}^n}{(\Delta&space;x)^2}&space;+&space;\frac{T_{i,j-1}^n&space;-&space;2T_{i,j}^n&space;+&space;T_{i,j+1}^n}{(\Delta&space;y)^2}\right)&space;+&space;S(i,j,n))

where n is the time step.

We can rearrange this equation as follows:

equation

where r = αΔt/(Δx)^2 and u = αΔt/(Δy)^2 are the discretization parameters, and f(i,j,n) = ΔtS(i,j,n) + T(i,j,n-1) is the right-hand side vector.

Finally, we can set up the coefficient matrix A and the right-hand side vector b as follows:

main.m
A = zeros((Nx-2)*(Ny-2));
b = zeros((Nx-2)*(Ny-2),1);

for i = 2:Nx-1
    for j = 2:Ny-1
        row = (i-2)*(Ny-2) + (j-1);
        col1 = (i-3)*(Ny-2) + (j-1);
        col2 = (i-1)*(Ny-2) + (j-1);
        col3 = (i-2)*(Ny-2) + (j-2);
        col4 = (i-2)*(Ny-2) + j;
        
        A(row,col1) = -r;
        A(row,col2) = 2*r+1;
        A(row,col3) = -u;
        A(row,col4) = 2*u+1;
    
        b(row) = f(i,j,n);    
    end
end
436 chars
20 lines

where Nx and Ny are the number of grid points in the x and y directions, respectively. The variables col1, col2, col3, and col4 correspond to the indices of the coefficients in the matrix A, and row corresponds to the index of the row. The coefficients are set up according to the discretization scheme described above.

Note that we have omitted the boundary points, which should be treated separately using boundary conditions.

gistlibby LogSnag