Plots coming out weird

4 views (last 30 days)
Precious
Precious on 9 Sep 2024
Commented: Voss on 9 Sep 2024
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

Answers (1)

Voss
Voss on 9 Sep 2024
Edited: Voss on 9 Sep 2024
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 Comments
Precious
Precious on 9 Sep 2024
Edited: Precious on 9 Sep 2024
pre-allocating fixed all my other sections! thank so much !
Voss
Voss on 9 Sep 2024
You're welcome! Any questions, let me know. Otherwise, please Accept this answer. Thanks!

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!