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