Plots coming out weird

4 次查看(过去 30 天)
Precious
Precious 2024-9-9
评论: Voss 2024-9-9
Not sure whats happening here. can someone help me
% Define the seeding point (x0,y0) = (2,-2)
xi= 2;
yi=-2;
% Define the time step for the integration
dt = 0.01;
% Initialize the trajectory at the seeding point
X(1)=xi;
Y(1)=yi;
for i=1:8
ui = 3*xi^2 ;
vi = 5*yi^ 2-xi.^3;
U(i)=ui;
V(i)=vi;
xi = xi +ui*dt ;
yi = yi + vi*dt ;
X(i+1) = xi; %store new positions
Y(i+1) = yi;
end
% Plot the trajectory in a new window
figure
plot(X,Y) %ploting particle trajectory

回答(1 个)

Voss
Voss 2024-9-9
编辑:Voss 2024-9-9
You likely have pre-existing X and Y variables in your workspace, which are being plotted in their entirety. Since the code shown only sets elements 1 through 9 in X and Y, any other elements that they contain will be unchanged.
To illustrate the problem:
% example random pre-existing X and Y
X = rand(100);
Y = 2*rand(100);
% Define the seeding point (x0,y0) = (2,-2)
xi= 2;
yi=-2;
% Define the time step for the integration
dt = 0.01;
% Initialize the trajectory at the seeding point
X(1)=xi;
Y(1)=yi;
for i=1:8
ui = 3*xi^2 ;
vi = 5*yi^ 2-xi.^3;
U(i)=ui;
V(i)=vi;
xi = xi +ui*dt ;
yi = yi + vi*dt ;
X(i+1) = xi; %store new positions
Y(i+1) = yi;
end
% Plot the trajectory in a new window
figure
plot(X,Y) %ploting particle trajectory
The best way to fix that is to (re-)initialize X and Y (and U and V) to be vectors of the appropriate size before your loop (i.e., pre-allocate them) so that there are no unintended elements hanging around, e.g.:
% pre-allocate vectors
N = 8;
X = zeros(1,N+1);
Y = zeros(1,N+1);
U = zeros(1,N);
V = zeros(1,N);
% Define the seeding point (x0,y0) = (2,-2)
xi= 2;
yi=-2;
% Define the time step for the integration
dt = 0.01;
% Initialize the trajectory at the seeding point
X(1)=xi;
Y(1)=yi;
for i=1:N
ui = 3*xi^2 ;
vi = 5*yi^ 2-xi.^3;
U(i)=ui;
V(i)=vi;
xi = xi +ui*dt ;
yi = yi + vi*dt ;
X(i+1) = xi; %store new positions
Y(i+1) = yi;
end
% Plot the trajectory in a new window
figure
plot(X,Y) %ploting particle trajectory
  3 个评论
Precious
Precious 2024-9-9
编辑:Precious 2024-9-9
pre-allocating fixed all my other sections! thank so much !
Voss
Voss 2024-9-9
You're welcome! Any questions, let me know. Otherwise, please Accept this answer. Thanks!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by