Error using plot. Vectors must be the same length.

Hello,
When running my code I'm getting the following error :
Error using plot
Vectors must be the same length.
Error in A5Q2 (line 45)
plot(x1,u(1,:),'*',x1,us1,'-');
Please find below my code:
function u = diff1_ex
ngrid = 50;
dx = 1/ngrid;
D=1;
s=0.4;
dt = s*dx^2/D;
tmin=0;
tmax=1;
ntime = ceil((tmax-tmin)/dt);
u = zeros(ngrid+1,ntime);
source=1;
for l=1:ntime
for k=2:ngrid
u(k,l+1)=u(k,l)+s*(u(k+1,l)-2*u(k,l)+u(k-1,l));
if (k>ceil((0.4/dx)-1)) && (k<ceil(0.6/dx))
u(k,1+l)=u(k,1+l)+ dt*source;
end
end
end
subplot(2,1,1);
imagesc(u);
colorbar;
xlabel('x')
ylabel('y')
x1 = 0:dx:1;
us1 = -0.3*x1;
x2 = 0.4:dx:0.6;
us2 = (-x2.^2)/2+(0.1*x2)-0.08;
x3 = 0.6:dx:1;
us3 = 0.5*(1-x3);
subplot(2,1,2);
hold on
plot(x1,u(1,:),'*',x1,us1,'-');
plot(x2,u(2,:),'*',x2,us2,'-');
plot(x3,u(3,:),'*',x3,us3,'-');
hold off
xlabel('x')
ylabel('us')
title('Stationary Solution')
Could you please help me to correct my mistake.
Please find attached the questions and my solution to the first question.
Thanks in advance

댓글 수: 5

Use the debugger and set a breakpoint after the line
u = zeros(ngrid+1,ntime);
look at
whos u
then at the plot() line try
length(u(1,:))
What do mean by " whos u " ?
When the debugger prompt shows up, type it in at the prompt.
See
doc whos
PS: By "at the plot line" I meant either set another breakpoint at that line and run until there or just step through until you get there (F10)
I'm really lost with the debugging process. Could you please help me going through it ? and figuring out the mistake
dpb
dpb 2018년 10월 28일
편집: dpb 2018년 10월 28일
Basically you just click on the line where you want a breakpoint in the editor and then press RUN since your function doesn't require any input arguments.
As a hint to your problem, look at how you defined the array u and then how you try to use it when you are trying to plot.
Learning to use the debugger is well worth the effort...

댓글을 달려면 로그인하십시오.

답변 (2개)

madhan ravi
madhan ravi 2018년 10월 28일

0 개 추천

plot(x1,u(1,1:numel(x1)),'*',x1,us1,'-');
plot(x2,u(2,1:numel(x2)),'*',x2,us2,'-');
plot(x3,u(3,1:numel(x3)),'*',x3,us3,'-');

댓글 수: 4

maybe like the above? not sure if its correct
Does not give me the right graph
ok then no idea because your x1, x2, x3 size is 1 by 51 and your u size is 51 by 6251 , how can you plot them?
I've posted more information below. Could you please check if I did something wrong in u , us1, us2, us3, x1, x2 and x3

댓글을 달려면 로그인하십시오.

Vashist Dwarka
Vashist Dwarka 2018년 10월 28일

0 개 추천

Please find attached the questions and the result of of the first question.

카테고리

도움말 센터File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

질문:

2018년 10월 28일

편집:

dpb
2018년 10월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by