How to Create a matching x vector for plot
Show older comments
Please look at the following code. I want to plot y vs. x. However I get the following error:
Error using plot. Vectors must be the same length. Error in orbitthreebody (line 12) plot(x,y)
I know that y is correct. How do I create a matching x vector so that I can make my plot?
function z=orbitthreebody(inter,ic,n,p)
h=(inter(2)-inter(1))/n; % plot n points
x1=ic(1);vx1=ic(2);y1=ic(3);vy1=ic(4); % grab initial conds
x2=ic(5);vx2=ic(6);y2=ic(7);vy2=ic(8);
x3=ic(9);vx3=ic(10);y3=ic(11);vy3=ic(12);
y(1,:)=[x1 vx1 y1 vy1 x2 vx2 y2 vy2 x3 vx3 y3 vy3];t(1)=inter(1); % build y vector
set(gca,'XLim',[-5 5],'YLim',[-5 5],'XTick',[-5 0 5],'YTick',[-5 0 5]);
x = linspace(0,12);
plot(x,y)
for k=1:n/p
for i=1:p
t(i+1)=t(i)+h;
y(i+1,:)=trapstep(t(i),y(i,:),h);
end
y(1,:)=y(p+1,:);t(1)=t(p+1);
clearpoints(head1);clearpoints(head2);clearpoints(head3);
addpoints(head1,y(1,1),y(1,3))
addpoints(tail1,y(1,1),y(1,3))
addpoints(head2,y(1,5),y(1,7))
addpoints(tail2,y(1,5),y(1,7))
addpoints(head3,y(1,9),y(1,11))
addpoints(tail3,y(1,9),y(1,12))
drawnow;
a=3;
axis([-a a -a a -a a])
frame=getframe;writeVideo(v,frame);
end
close(v)
function y=eulerstep(t,x,h)
y=x+h*ydot(t,x);
function y = trapstep(t,x,h)
z1=ydot(t,x);
g=x+h*z1;
z2=ydot(t+h,g);
y=x+h*(z1+z2)/2;
function z = ydot(t,x)
m1=0.03;
m2=0.3;
m3=0.03;
g=1;mg1=m1*g;mg2=m2*g;mg3=m3*g;
px1=x(1);py1=x(3);pz1=x(5);vx1=x(2);vy1=x(4);vz1=x(6);
px2=x(7);py2=x(9);pz2=x(11);vx2=x(8);vy2=x(10);vz2=x(12);
px3=x(13);py3=x(15);pz3=x(17);vx3=x(14);vy3=x(16);vz3=x(18);
dist12=sqrt((px2-px1)^2+(py2-py1)^2+(pz2-pz1)^2);
dist23=sqrt((px2-px3)^2+(py2-py3)^2+(pz2-pz3)^2);
dist13=sqrt((px1-px3)^2+(py1-py3)^2+(pz1-pz3)^2);
z=zeros(1,12);
z(1)=vx1;
z(2)=(mg2*(px2-px1))/(dist12^3)+(mg3*(px3-px1))/(dist13^3);
z(3)=vy1;
z(4)=(mg2*(py2-py1))/(dist12^3)+(mg3*(py3-py1))/(dist13^3);
z(5)=vx2;
z(6)=(mg1*(px1-px2))/(dist12^3)+(mg3*(px3-px2))/(dist23^3);
z(7)=vy2;
z(8)=(mg1*(py1-py2))/(dist12^3)+(mg3*(py3-py2))/(dist23^3);
z(9)=vx3;
z(10)=(mg1*(px1-px3))/(dist13^3)+(mg2*(px2-px3))/(dist23^3);
z(11)=vy3;
z(12)=(mg1*(py1-py3))/(dist13^3)+(mg2*(py2-py3))/(dist23^3);
Answers (1)
Star Strider
on 18 Dec 2021
I can’t run the code because I have no idea what the arguments are.
That aside, try this —
x = linspace(0,12,numel(y));
plot(x,y)
That should equalise the lengths, and the plot should work.
I have no idea if it solves any other problems that could be present in the code.
.
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!