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 Kommentare

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 am 28 Okt. 2018
Bearbeitet: dpb am 28 Okt. 2018
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...

Melden Sie sich an, um zu kommentieren.

Antworten (2)

madhan ravi
madhan ravi am 28 Okt. 2018
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 Kommentare

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

Melden Sie sich an, um zu kommentieren.

Vashist Dwarka
Vashist Dwarka am 28 Okt. 2018

0 Stimmen

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

Kategorien

Mehr zu Get Started with MATLAB finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 28 Okt. 2018

Bearbeitet:

dpb
am 28 Okt. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by