How to show the iterations and the answers and the graph
4 views (last 30 days)
Show older comments
clc
clear
m = 68.1;
g = 9.81;
t = 10;
v = 40;
f =@(c) (g*m*(1-(exp((-c*t)/m)))/c)-v;
N = 100; %iterations
err = 0.1;
c = 0.1:0.1:50;
x1 = c(1);
xu = c(end);
%root check
S = f(x1)*f(xu);
if S > 0
error('No root');
else
for i = 1:N
xr = xu - (f(xu)*(x1-xu))/(f(x1)-f(xu));
S = f(xr)*f(xu);
if S < 0
x1 = xr;
xr = xu - (f(xu)*(x1-xu))/(f(x1)-f(xu));
Err = abs(xr - x1);
if Err < err
break;
end
else if S > 0
xu = xr;
xr = xu - (f(xu)*(x1-xu))/(f(x1)-f(xu));
Err = abs(xr - xu);
if Err < err
break;
end
else
break;
end
ii = i;
end
end
end
disp(['The Root is: ' num2str(xr) ',with accuracy: ' num2str(Err) ', NO Iteration:' num2str(ii)]);
this is my finished code and how do i display the loop of this function? and also the display of the graph
0 Comments
Answers (1)
David Hill
on 3 May 2021
Why not use a while loop?
m = 68.1;
g = 9.81;
t = 10;
v = 40;
f =@(c) (g*m*(1-(exp((-c*t)/m)))/c)-v;
err = 1e-10;
c = 0.1:0.1:50;
x1 = c(1);
xu = c(end);
%root check
S = f(x1)*f(xu);
if S > 0
error('No root');
else
Err=1;
count=1;
while Err>err
xr(count) = xu - (f(xu)*(x1-xu))/(f(x1)-f(xu));
S = f(xr(count))*f(xu);
if S < 0
Err = abs(xr(count) - x1);
x1 = xr(count);
else
Err = abs(xr(count) - xu);
xu = xr(count);
end
count=count+1;
end
disp(['The Root is: ' num2str(xr(count-1)) ',with accuracy: ' num2str(Err)...
', NO Iteration:' num2str(count-1)]);
plot(1:count-1,xr)%this plots iterations vs. xr
end
0 Comments
See Also
Categories
Find more on Environment and Settings 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!