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 Center および File ExchangeSurface and Mesh Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by