For the following code, It shows my 51 iterations, however i only want to display the last iteration

3 次查看(过去 30 天)
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

回答(1 个)

the cyclist
the cyclist 2021-3-4
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 个评论
the cyclist
the cyclist 2021-3-4
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)]);
Error as percentage: 2.6577e-13
disp(['friction factor: ', num2str(xLeft)]);
friction factor: 0.023498
disp(['Solution reached in ',num2str(nIteration),' iterations']);
Solution reached in 51 iterations
Ben Spurr
Ben Spurr 2021-3-4
I have just adjusted my code and the output gives just the values i want. It seems that the problem was that the disp functions should be after the initial for loop closes. Thanks for the help and looks good now!

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by