matlab index out of bounds because numel
2 次查看(过去 30 天)
显示 更早的评论
Can you help me with this code:
function [r, niter] = fpiter(g,x0,maxiter)
i = 1;
x(1,:) = x0;
tol = 1e-05;
while i <= maxiter
x(i+1,:) = g(x(i,:));
if abs(x(i+1,:)-x(i,:)) < tol %stopping criterion
disp('The procedure was successful after k iterations')
niter = i
disp('The root to the equation is')
r = x(i+1)
return
end
i = i+1;
end
if abs(x(i)-x(i-1)) > tol | i > N
disp('The procedure was unsuccessful')
disp('Condition |p(i+1)-p(i)| < tol was not sastified')
tol
disp('Please, examine the sequence of iterates')
x = x'
disp('In case you observe convergence, then increase the maximum number of iterations')
disp('In case of divergence, try another initial approximation p0 or rewrite g(x)')
disp('in such a way that |g''(x)|< 1 near the root')
end
Here's the g function:
function y = g(x)
y = x.^2 - 2.*x + 1;
I got this error when I'm running it with the code: fpiter('g',1, 5)
Attempted to access g(103); index out of bounds because numel(g)=1.
Error in fpiter (line 6)
x(i+1) = g(x(i));
Thank you :)
0 个评论
回答(1 个)
Walter Roberson
2013-3-1
Run the code as
fpiter(@g,1, 5)
5 个评论
Walter Roberson
2013-3-2
Your routine does do fixed-point iteration. However, it happens that for every quadratic that does not happen to have a certain specific relationship of coefficients, that there are two fixed point values, x = g(x), and two more fixed point values, x = g(g(x)), and four more fixed point values x = g(g(g(x))) . Some of these roots are likely to be imaginary.
In any case, as you are looking for roots of the polynomial, you should be adding the check g(x) == 0, because no matter whether the difference between x and g(x) is less than the tolerance, if g(x) is 0 then x is a root.
另请参阅
类别
在 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!