For the following code, It shows my 51 iterations, however i only want to display the last iteration
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
clc; clear all; close all;
prompt = 'What is the value of the relative pipe roughness, e/d? ';
m = input(prompt);
prompt = 'What is the value of the Reynolds number, Re? ';
Re = input(prompt);
g=@(f) 1/sqrt(f) + 2*log10((m*1/3.71)+2.51/(Re*sqrt(f)));
xLeft = 0.008; % lower limit x value initial guess
xRight = 0.08; % upper limit x value initial guess
fLeft = g(xLeft); % function of xLeft
fRight = g(xRight); % function of xRight
nIteration = 0;
if (fLeft*fRight>0)
error('The fLeft and fRight value should have different signs');
end
for i = 0:50
err = abs((xLeft-xRight)/xLeft)*100;
xAvg = (xLeft+xRight)/2;
fAvg = g(xAvg);
if (fAvg*fLeft>0)
xLeft = xAvg;
fLeft = fAvg;
else
xRight = xAvg;
fRight = fAvg;
end
nIteration = nIteration+1;
disp(['Error as percentage: ',num2str(err)]);
disp(['friction factor: ', num2str(xLeft)]);
disp(['Solution reached in ',num2str(nIteration),' iterations']);
end
Réponses (1)
the cyclist
le 4 Mar 2021
Looks like you could just pull these lines out, and put them after the end statement of the loop:
disp(['Error as percentage: ',num2str(err)]);
disp(['friction factor: ', num2str(xLeft)]);
disp(['Solution reached in ',num2str(nIteration),' iterations']);
7 commentaires
the cyclist
le 4 Mar 2021
Running your code right here, and I see only the last iteration's results displayed. Not sure why you have something else.
clc; clear all; close all;
% prompt = 'What is the value of the relative pipe roughness, e/d? ';
% m = input(prompt);
m = 0.002;
% prompt = 'What is the value of the Reynolds number, Re? ';
% Re = input(prompt);
Re = 2e6;
g=@(f) 1/sqrt(f) + 2*log10((m*1/3.71)+2.51/(Re*sqrt(f)));
xLeft = 0.008; % lower limit x value initial guess
xRight = 0.08; % upper limit x value initial guess
fLeft = g(xLeft); % function of xLeft
fRight = g(xRight); % function of xRight
nIteration = 0;
if (fLeft*fRight>0)
error('The fLeft and fRight value should have different signs');
end
for i = 0:50
err = abs((xLeft-xRight)/xLeft)*100;
xAvg = (xLeft+xRight)/2;
fAvg = g(xAvg);
if (fAvg*fLeft>0)
xLeft = xAvg;
fLeft = fAvg;
else
xRight = xAvg;
fRight = fAvg;
end
nIteration = nIteration+1;
end
% These lines are now outside the for loop
disp(['Error as percentage: ',num2str(err)]);
disp(['friction factor: ', num2str(xLeft)]);
disp(['Solution reached in ',num2str(nIteration),' iterations']);
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!