while loop in a for loop
1 view (last 30 days)
Show older comments
Siti Jamilah Binti Mohd Yatim
on 15 Apr 2021
Commented: Mathieu NOE
on 19 Apr 2021
hello. i am trying to plot a graph of ut (terminal velocity) against D (diameter) and my code is as below. i can plot the data but somehow the graph is not what i expected it to be. can someone help me? thank you in advance!
% m-file to plot ut vs D
D=0:1e-3:5e-3;
ut=miniclasstest1920_i(D);
plot(D,ut);
[D(1) ut(1)];
[D(end) ut(end)];
ut1=miniclasstest1920_i(1e-5);
ut2=miniclasstest1920_i(5e-3);
[ut1 ut2]
% function miniclasstest1920_i
function ut=f(D)
rho_s=2350;
rho=1100;mu=2e-3;
g=9.81;
LD=length(D);
ut=zeros(LD,1);
for n=1:LD
u=zeros(10,1);
Re=zeros(10,1);
u(1)=1e-5;
Re(1)=(rho*u(1).*D(n))/mu;
err(1)=abs(Re(1)-0);
i=1;
while err(i)>1e-6
if Re(i)<0.2
u(i+1)=((g*D(n).^2)*(rho_s-rho))/(18*mu);
Re(i+1)=(rho*u(i+1)*D(n))/mu;
elseif 500<Re(i)<2e5
u(i+1)=sqrt((3.*D(n)*g*(rho_s-rho))/rho);
Re(i+1)=(rho*u(i+1)*D(n))/mu;
else
disp('odd')
end
i=i+1;
err(i)=abs(Re(i)-Re(i-1));
end
end
u=u(1:i-1);
ut(n)=u(end);
end
6 Comments
Accepted Answer
Mathieu NOE
on 19 Apr 2021
hello again
official answer below :
code fixed !! the output of the function was incorrect (wrong index and not at the right position in the loop structure)
% m-file to plot ut vs D
D=0:1e-3:5e-3;
ut=f(D);
plot(D,ut);
function ut=f(D)
rho_s=2350;
rho=1100;
mu=2e-3;
g=9.81;
LD=length(D);
ut=zeros(LD,1);
for n=1:LD
u=zeros(10,1);
Re=zeros(10,1);
u(1)=1e-5;
Re(1)=(rho*u(1).*D(n))/mu;
err(1)=abs(Re(1)-0);
ci=1;
while err(ci)>1e-6
if Re(ci)<0.2
u(ci+1)=((g*D(n).^2)*(rho_s-rho))/(18*mu);
Re(ci+1)=(rho*u(ci+1)*D(n))/mu;
elseif 500<Re(ci)<2e5
u(ci+1)=sqrt((3.*D(n)*g*(rho_s-rho))/rho);
Re(ci+1)=(rho*u(ci+1)*D(n))/mu;
else
disp('odd')
ci
end
ci=ci+1;
err(ci)=abs(Re(ci)-Re(ci-1));
end
ut(n)=u(ci) ; % and not u(end)
end
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!