Alqosh Hazkeal
Alqosh Hazkeal

Reputation: 1

how to find newton iteration for each of initial points

 function p = newton_hw(p0,tol,Nmax)

%NEWTON'S METHOD: Enter f(x), f'(x), x0, tol, Nmax
f = @(x) x*cos(x)-((sin(x))^2);
fp= @(x) -x*sin(x)+ cos(x)-2*sin(x)*cos(x);
p = p0 - (f(p0)/fp(p0));
y1=f(p);
fprintf('y1=%f',y1)
i = 1;
while (abs(p - p0) >= tol)

    p0 = p;
    p = p0 - f(p0)/fp(p0);
    i = i + 1;
    if (i >= Nmax)
        fprintf('Fail after %d iterations\n',Nmax);
        break
    end

    y=f(p);
    fprintf('a=%f,y=%f,\n',p,y);
end

end

This is my question:

How to iterate for each of p0 = 0,.1,.2,...,49,5.

Upvotes: 0

Views: 51

Answers (1)

Mikhail_Sam
Mikhail_Sam

Reputation: 11208

Iterating using user's step can be done this way:

for i = 0:0.1:5

Also any indexing can be done the same way: x = [0:2:50].

If your function works correctly (I suppose so), we can go this way:

k = 1;
for i = 0:0.1:5
res(k) = newton_hw(i,0.001,1000);
k = k+1;
end 

But also we can do it at one line - style:

res = arrayfun( @(x) newton_hw(x, 0.001, 1000), I)

Upvotes: 1

Related Questions