code is right but can not the a plot

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 个评论

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.

请先登录,再进行评论。

 采纳的回答

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 个)

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

类别

帮助中心File Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by