Plots coming out weird
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (1)
Voss
le 9 Sep 2024
Modifié(e) : Voss
le 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 commentaires
Voss
le 9 Sep 2024
You're welcome! Any questions, let me know. Otherwise, please Accept this answer. Thanks!
Voir également
Catégories
En savoir plus sur Surface and Mesh Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!