You are on page 1of 1

MATLAB Command Window Page 1

>> % Parameters
L = 2; % Length of the rod
T = 1; % Final time
h = 1/4; % Spatial step size
k = 1/40; % Time step size
N = round(L/h) + 1; % Number of spatial points (rounded to the nearest integer)
M = round(T/k) + 1; % Number of time steps (rounded to the nearest integer)

% Initial condition
u0 = zeros(N, 1);
u0(1:N/2) = 1;

% Boundary conditions
u0(1) = 0;
u0(end) = 0;

% Finite difference scheme


r = k/(h^2);
u = u0;
for n = 2:M
u_new = zeros(N, 1);
for i = 2:N-1
u_new(i) = u(i) + r * (u(i+1) - 2*u(i) + u(i-1));
end
u = u_new;
end

% Plotting
x = linspace(0, L, N);
plot(x, u, 'LineWidth', 2);
title('Solution of Heat Equation at t = 1' );
xlabel('x');
ylabel('u(x,1)');
ylim([0, 1.2]); % Adjust ylim as needed
grid on;
Warning: Integer operands are required for colon operator when used as index.

>>

You might also like