code is right but can not the a plot

2 views (last 30 days)
Hello, I do not what the mistake is? I'm getting the first plot. However, I have not been able to get the second plot. Not sure how to fix it. As alwyas any help will be greatly appreciated. Thanks
clear
clc
L = 1-0;
T = 0.06-0;
alpha = 1;
dx = 0.05;
dt = 0.001;
%Q = (alpha.*dt)/(dx.^2);
Q = 0.25;
N = L/dx +1;
M = T/dt + 1;
x = zeros(N,1);
t = zeros(M,1);
for i=1:N
x(i) = 0+(i-1).*dx;
end
for n=1:M
t(n) = 0+(n-1).*dt;
end
u = zeros(M,N);
u(:,1) = 2;
u(:,N) = 1;
u(1,2:N-1) = sin(pi.*x(2:N-1));
for n=1:M
for i=2:N-1
u(n+1,i) = Q.*u(n,i+1) + (1-2*Q).*u(n,i) + Q.*u(n,i-1)
end
end
figure(1)
plot (x,u(M,:)) %plot x vs u
title ('x vs u at t = 0.06')
xlabel ('x')
ylabel ('T')
grid on
figure(2)
plot(t, u(:,N-1)) %plot t vs u
title ('t vs u at x = 0.5')
xlabel ('time')
ylabel ('T')
  1 Comment
Cesar Cardenas
Cesar Cardenas on 5 Mar 2023
thank you. could you show me the lines where the problem is? I did not write the whole code, I just added a couple of lines to plot. Thank you.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 5 Mar 2023
Edited: Star Strider on 5 Mar 2023
You need to redefine ‘t’ so that it matches the row size of ‘u’:
t = linspace(0, 2.5, size(u,1));
Try this —
% clear
% clc
L = 1-0;
T = 0.06-0;
alpha = 1;
dx = 0.05;
dt = 0.001;
%Q = (alpha.*dt)/(dx.^2);
Q = 0.25;
N = L/dx +1;
M = T/dt + 1;
%x = zeros(N,1);
x = linspace(0, 2.5, 5);
% t = linspace(0, 2.5, 5);
%t = zeros(M,1);
for i=1:N
x(i) = 0+(i-1).*dx;
end
for n=1:M
t(n) = 0+(n-1).*dt;
end
u = zeros(M,N);
u(:,1) = 2;
u(:,N) = 1;
u(1,2:N-1) = sin(pi.*x(2:N-1));
for n=1:M
for i=2:N-1
u(n+1,i) = Q.*u(n,i+1) + (1-2*Q).*u(n,i) + Q.*u(n,i-1);
end
end
figure(1)
plot (x,u(M,:)) %plot x vs u
title ('x vs u at t = 0.06')
xlabel ('x')
ylabel ('T')
grid on
t = linspace(0, 2.5, size(u,1)); % Redefine 't' To Match 'u'
figure(2)
plot(t, u(:,N-1)) %plot t vs u
title ('t vs u at x = 0.5')
xlabel ('time')
ylabel ('T')
EDIT — Forgot to re-run code before posting. Now run.
.
  1 Comment
Torsten
Torsten on 5 Mar 2023
By changing t before plotting, u(:,N-1) is plotted at the wrong times.

Sign in to comment.

More Answers (1)

Torsten
Torsten on 5 Mar 2023
Edited: Torsten on 5 Mar 2023
If you compare size(t) and size(u,1), you will find that the number of elements of both vectors are not the same (they differ by one element). Thus the second plot command errors.
Replace
for n=1:M
for i=2:N-1
u(n+1,i) = Q.*u(n,i+1) + (1-2*Q).*u(n,i) + Q.*u(n,i-1)
end
end
by
for n=1:M-1
for i=2:N-1
u(n+1,i) = Q.*u(n,i+1) + (1-2*Q).*u(n,i) + Q.*u(n,i-1)
end
end

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!