What is wrong with the function code when it can work perfectly without function code
1 次查看(过去 30 天)
显示 更早的评论
Hi There!
I am having trouble on my code where I made the code in function [input] = f(output) doesn't give me the expected answer but a normal script do.
function [k,p,err,P] = fixpt(g,po,tol,maxi)
% g is the function input as function handle
% po is the first guess
% tol is the tolerance
% maxi is the maximum iteration
% K is the number of iteration
% p is the sequence {pn}
% error is the absolute error
P(1) = po
for k = 2:maxi
P(k) = g(P(k-1));
err = abs(P(k) - P(k-1));
relerr = (err/abs(P(k)));
p = P(k);
if abs(err)<tol || abs(relerr)<tol
return
end
end
if k == maxi
fprintf('Iteration exceed maximum.')
end
end
If I do run it:
fixpt(@(x) sin(x)-1,-1,0.001,100)
It doesn't give me the the answer I expected whereas:
g = @(x) sin(x)-1
maxi = 100
tol = 0.00001
po = -1
P(1) = po
for k = 2:maxi
P(k) = g(P(k-1));
err = abs(P(k) - P(k-1));
relerr = (err/abs(P(k)));
p = P(k);
if abs(err)<tol || abs(relerr)<tol
return
end
end
if k == maxi
fprintf('Iteration exceed maximum.')
end
This does.
Im using R2021a. Thank you.
0 个评论
采纳的回答
Torsten
2022-10-6
编辑:Torsten
2022-10-6
Works for me.
[k,p,err,P] = fixpt(@(x) sin(x)-1,-1,0.00001,100)
function [k,p,err,P] = fixpt(g,po,tol,maxi)
% g is the function input as function handle
% po is the first guess
% tol is the tolerance
% maxi is the maximum iteration
% K is the number of iteration
% p is the sequence {pn}
% error is the absolute error
P(1) = po;
for k = 2:maxi
P(k) = g(P(k-1));
err = abs(P(k) - P(k-1));
relerr = (err/abs(P(k)));
p = P(k);
if abs(err)<tol || abs(relerr)<tol
return
end
end
if k == maxi
fprintf('Iteration exceed maximum.')
end
end
6 个评论
更多回答(1 个)
Davide Masiello
2022-10-6
编辑:Davide Masiello
2022-10-6
The value of for tol differs of two orders of magnitude in the examples you gave (i.e., you used 0.001 in the function call, 0.00001 in the functionless script).
[k,p,err,P] = fixpt(@(x) sin(x)-1,-1,0.00001,100)
function [k,p,err,P] = fixpt(g,po,tol,maxi)
% g is the function input as function handle
% po is the first guess
% tol is the tolerance
% maxi is the maximum iteration
% K is the number of iteration
% p is the sequence {pn}
% error is the absolute error
P(1) = po
for k = 2:maxi
P(k) = g(P(k-1));
err = abs(P(k) - P(k-1));
relerr = (err/abs(P(k)));
p = P(k);
if abs(err)<tol || abs(relerr)<tol
return
end
end
if k == maxi
fprintf('Iteration exceed maximum.')
end
end
Is this correct?
3 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!