How to solve method of lines on one-dimensional heat equation using Euler's method?
19 views (last 30 days)
Show older comments
I have tried but I couldn't solve it fully. Here i attach my code and the question.![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1250337/image.jpeg)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1250337/image.jpeg)
% Parameters
k = 0.5;
% Evaluate BC
N = 3;
u(0)= 0;
u(1:N)= U;
u(N+1)=0;
h = 1/(N+1) ; %step size
%Initial condition
for i=1:N
u(i)=sin(pi*i);
end
% Define du/dt
dudt = zeros (N+1,1);
for i=1:N
dudt(i)=k/h^2*(u(i-1)-2*u(i)+u(i+1));
end
1 Comment
Torsten
on 3 Jan 2023
Edited: Torsten
on 3 Jan 2023
u(0)= 0;
Array indices start with 1, not with 0. Thus u(0) will throw an error.
u(1:N)= U;
You did not yet define U.
u(i)=sin(pi*i);
i must be replaced by x(i) if 0=x(1)<x(2)<...<x(N+2)=1 is your grid in x-direction. And using N+2 grid points, your loop limits 1 and N are wrong.
dudt = zeros (N+1,1);
You use N+2 grid points.
for i=1:N
dudt(i)=k/h^2*(u(i-1)-2*u(i)+u(i+1));
end
Loop limits are wrong.
You must advance u in time by dudt, so something like u(n+1,i) = u(n,i) + dt * dudt(i) is missing where the "n" refers to the solution at time dt*n.
Accepted Answer
Torsten
on 3 Jan 2023
Edited: Torsten
on 4 Jan 2023
% Parameters
k = 0.5;
% Evaluate BC
dx = 0.01;
x = 0:dx:1;
dt = 0.0001;
t = 0:dt:0.5;
h = 1/(length(x)-1) ; %step size
u = zeros(length(t),length(x));
%Initial condition
for i=1:length(x)
u(1,i)=sin(pi*x(i));
end
for j = 1:length(t)-1
for i=2:length(x)-1
u(j+1,i) = u(j,i) + dt* k/dx^2*(u(j,i-1)-2*u(j,i)+u(j,i+1));
end
end
figure(1)
plot(x,[u(1,:);u(500,:);u(1000,:);u(2000,:);u(5000,:)])
figure(2)
surf(x,t,u,'Edgecolor','none')
6 Comments
Ankitha
on 4 Jan 2023
Edited: Ankitha
on 4 Jan 2023
@Torsten could you please have a look at my question as well https://de.mathworks.com/matlabcentral/answers/1888402-how-to-solve-heat-equation-using-euler-cauchy-method?s_tid=srchtitle ? iit would be really great. Thank you
More Answers (0)
See Also
Categories
Find more on Downloads in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!