how to change the code below with while loop to for loop?

조회 수: 1 (최근 30일)
Nilly
Nilly 2018년 1월 17일
답변: Mihir 2023년 6월 18일
I would like to change this while loop to for loop and is there any way to re-code it without mod(c,2500)?
% code
dx = 1;
x = 0:dx:1000;
x(end) = [];
u = zeros(size(x));
u(x<=220) = 1;
t = 0;
dt = 450;
uinit = u;
k = 0.001;
s = 0.22;
tend = 4000000;
v = s*k;
c = 1;
vmax = 0;
unew(1,:) = uinit;
front1 = 0.75*min(uinit)+0.25*max(uinit);
front2 = 0.25*min(uinit)+0.75*max(uinit);
front = length(uinit([uinit>front1 & uinit<front2]));
figure(1)
plot(x,uinit)
hold on
while t < tend
D = k*u;
D = (D([2:end,1])+D)/2;
dudx = (u([2:end,1])-u)/dx;
q = -D.*dudx+u*v;
u = u - dt * (q-q([end,1:end-1]))/dx;
if mod(c,2500)==0
plot(x,u)
unew(end+1,:) = u;
end
front1 = 0.75*min(u)+0.25*max(u);
front2 = 0.25*min(u)+0.75*max(u);
front(end+1) = length(u([u>front1 & u< front2]));
vmax(end+1) = max(k*(s+dudx));
t = t+dt;
c = c+1;
end

답변 (1개)

Mihir
Mihir 2023년 6월 18일
Hi, the replacement of the outer while loop by the for loop can be made by firstly declaring the upperbound of the for loop (num_plots) in the below code and for replacing the inner if condition, you can write one more for loop the runs for 2500 times. So basically nested for loops will meet the requirements.
num_plots = floor(tend / dt / 2500);
for plot_index = 1:num_plots
for c = 1:2500
Perform the operations here
end
plot(x,u)
unew(end+1,:) = u;
end

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by