Matlab: While loop use end values

2 次查看(过去 30 天)
MrLefouf
MrLefouf 2022-3-30
I have a script with a for loop in matlab which runs 3 scripts multiple times (ex: k=100). These scripts generate different input values each time that need to be used in the last script. The last script includes a while loop, which need to use the input values from the previous scripts in every run . I would like to then use the final x(end) value of each run of the while loop for these k inputs, for further calculations. Problem = i only get 1 identical value for my 100 times i run these scripts. From the other scripts i get 100 correct, different results, following the predefined variations.
nsamples=100;
for k = 1:nsamples;
scriptA
scriptB
scriptC
k=k+1;
end
ScriptC contains the while loop.
while min(y)> -0.01;
t = t + dt;
i = i + 1;
xf(i) = xf(i-1)+ Vx.*dt;
AxD = - ( D / Mass ) * V * Vx;
AyD = -G - ( D / Mass ) * V * Vy;
Vx = Vx + AxD * dt;
Vy = Vy + AyD * dt;
x(i) = x(i-1) + Vx * dt + 0.5 * AxD * dt^2;
y(i) = y(i-1) + Vy * dt + 0.5 * AyD * dt^2;
end;
I get 100 of the same values for x(end), instead of 100 different ones, based on the different input from the previous scripts (which i can verify in a table with all the different relevant (k) values). That is my problem = how can i obtain and use the x(end) or max(x) value of each of the (k) runs?

回答(1 个)

Mathieu NOE
Mathieu NOE 2022-3-30
hello
try my little demo below
clc
clearvars
nsamples=10;
for k = 1:nsamples
% constants init (my guess / demo)
D = 1;
Mass = 1;
G = 0.1;
V = -1e-3;
Vx = 1e-2+ 1e-2*k;
Vy = 1e-3+ 1e-2*k;
% init recursion arrays
clear t xf x y % mandatory !
t(1) = 0;
n = 1 ;
dt = 1e-2;
x(1) = -1;
xf(1) = 0.5;
y(1) = 0.1;
while min(y)> -0.01
n = n + 1;
t(n) = t(n-1) + dt;
xf(n) = xf(n-1)+ Vx.*dt;
AxD = - ( D / Mass ) * V * Vx;
AyD = -G - ( D / Mass ) * V * Vy;
Vx = Vx + AxD * dt;
Vy = Vy + AyD * dt;
x(n) = x(n-1) + Vx * dt + 0.5 * AxD * dt^2;
y(n) = y(n-1) + Vy * dt + 0.5 * AyD * dt^2;
end
t_end(k) = t(end-1); % sample before "end" to make sure the criteria is met
x_end(k) = x(end-1); % sample before "end" to make sure the criteria is met
y_end(k) = y(end-1); % sample before "end" to make sure the criteria is met
figure(k)
plot(t,y,'-*',t_end(k),y_end(k),'dr')
end

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by