How to change variable's value in a for loop with a few equations?

2 次查看(过去 30 天)
Hello guys, I would like to ask you for help with my FOR LOOP. I was able to create FOR LOOP, but I need to create WHILE or IF LOOP inside the FOR LOOP, that would change the step h in first equation. I have been doing that for a few days, but no results so far.
For detail. If the variable z(i) is higher than 1, then the step h is about to change. I have tried to put the IF LOOP inside right after the first equation, however, I have always got an error with the row where the IF LOOP starts. The z(i) or psi(i) are supposed to equal 1,000, which means, if the value is higher than 1,0, the step h must be decreased. The number of increments depends on the value of z(i) or psi(i), so the 260 value is not important.
Hope it is understandable for you and thank you for your reactions!
% Internal Balistics - HomeWork
clear all
clc
% Parameters
om = 0.4;
f = 0.92e6;
del = 1600;
Ik = 0.952e6;
alfa = 0.00092;
c0 = 2e-3;
kap = 2.175;
kaplam = -1.35;
kapmy = 0.175;
h = 0.0001;
z0 = 0.0;
p0 = 0.1e6;
t0 = 0.0;
%initial conditions
z(1) = z0;
p(1) = p0;
t(1) = t0;
%for cycle
for i=1:1:260
z(i+1) = z(i)+h*(p(i)/Ik);
psi(i+1) = kap*z(i+1)+(kaplam*z(i+1)^2)+kapmy*z(i+1)^3;
p(i+1) = (f*om*psi(i+1))/(c0-om/del*(1-psi(i+1))-alfa*om*psi(i+1));
t(i+1) = t(i) + h;
end
disp('Max pressure is')
p(i)
plot(t,p,'r','linewidth',3);
xlabel('Time [s]','fontsize',15);
ylabel('Presure [Pa]','fontsize',15);
grid on;

回答(1 个)

Ronit
Ronit 2025-5-30
Unfortunately, a "for" loop is not ideal because it has a fixed number of iterations. If you want to change "h" dynamically, it's better to use a "while" loop, which lets you control how "h" changes and when the loop ends.
Refer to the following code implementation using the "while" loop:
% Parameters
om = 0.4;
f = 0.92e6;
del = 1600;
Ik = 0.952e6;
alfa = 0.00092;
c0 = 2e-3;
kap = 2.175;
kaplam = -1.35;
kapmy = 0.175;
h = 0.0001;
z0 = 0.0;
p0 = 0.1e6;
t0 = 0.0;
%initial conditions
z(1) = z0;
p(1) = p0;
t(1) = t0;
i = 1;
while t(i) < 0.026 % equivalent to 260 steps of h=0.0001
z(i+1) = z(i) + h*(p(i)/Ik);
psi(i+1) = kap*z(i+1) + (kaplam*z(i+1)^2) + (kapmy*z(i+1)^3);
p(i+1) = (f*om*psi(i+1)) / (c0 - om/del*(1 - psi(i+1)) - alfa*om*psi(i+1));
t(i+1) = t(i) + h;
% Check if z(i+1) or psi(i+1) > 1, reduce step
if z(i+1) > 1 || psi(i+1) > 1
h = h / 2; % reduce time step
end
i = i + 1;
end
disp('Max pressure is')
Max pressure is
disp(max(p))
2.2547e+08
plot(t, p, 'r', 'LineWidth', 3);
xlabel('Time [s]', 'FontSize', 15);
ylabel('Pressure [Pa]', 'FontSize', 15);
grid on;
I hope this resolves your query!
Thanks

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by