DNilla
DNilla

Reputation: 43

Matrix dimensions must agree, Newton method

I need to find roots of a function using Newton method. I enter interval and accuracy from keyboard. Here is my code

disp('Newton method')
fx=@(g) 5*sin(g.^3-2*g.^2-1);
fx1=@(g) 5*g*(3*g-4)*cos(-g.^3+2*g.^2+1);
fx2=inline('-5*((4-6*g)*cos(-g.^3+2*g.^2+1)-(4*g-3*g.^2).^2*sin(-g.^3+2*g.^2+1))'); 
e=input ('Enter accuracy:');
a=input ('enter a:');
b=input ('enter b:');
x0=a:e:b;
y= 5*sin(x0.^3-2*x0.^2-1);
y2= -5*((4-6*x0)*cos(-x0.^3+2*x0.^2+1)-(4*x0-3*x0.^2).^2*sin(-x0.^3+2*x0.^2+1));
plot (x0,y),grid
xlabel('x'),ylabel('y')
fa=fx(a);
n=0;
if (fa*y2>0)
    x1=a;
else
    x1=b;

end;
 while(abs(fx(x1))>e)
       n=n+1;
    x1=x1-(fx(x1))/(fx1(x1));

 end;
 disp(sprintf('Answer:%g',x1))
    disp(sprintf('Number of iterations:%g',n))

When I compile, it says:

Error using  * 
Inner matrix dimensions must agree.

Error in Untitled3 (line 10)
y2= -5*((4-6*x0)*cos(-x0.^3+2*x0.^2+1)-(4*x0-3*x0.^2).^2*sin(-x0.^3+2*x0.^2+1));

Upvotes: 0

Views: 136

Answers (1)

Daniel
Daniel

Reputation: 36720

You are multiplying two 1xn vectors, that is not possible. This multiplication causes the error:

y2= -5*((4-6*x0)*cos(-x0.^3+2*x0.^2+1)-(4*x0-3*x0.^2).^2*sin(-x0.^3+2*x0.^2+1));
                ^                                       ^
                |                                       |

Using element-wise multiplication .* might be the solution, but I don't know what you try to implement.

Upvotes: 1

Related Questions