Error code line 19 with my Y=f(x), equation used is x^3+x^2-4x-4
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
ky win
am 28 Sep. 2024
Kommentiert: Walter Roberson
am 29 Sep. 2024
function [x,y,err]=muller(f,x0,x1,x2,delta,epsilon,max1)
%Input - f is the object function
% - x0, x1, and x2 are the initial approximations
% - delta is the tolerance for x0, x1, and x2
% - epsilon the the tolerance for the function values y
% - max1 is the maximum number of iterations
%Output- x is the Muller approximation to the zero of f
% - y is the function value y = f(x)
% - err is the error in the approximation of x.
%Initalize the matrices X and Y
X=[x0 x1 x2];
Y=f(X);
%Calculate a and b in formula (15)
for k=1:max1
h0=X(1)-X(3);h1=X(2)-X(3);e0=Y(1)-Y(3);e1=Y(2)-Y(3);c=Y(3);
denom=h1*h0^2-h0*h1^2;
a=(e0*h1-e1*h0)/denom;
b=(e1*h0^2-e0*h1^2)/denom;
%Find the smallest root of (17)
if b < 0
disc=-disc;
end
z=-2*c/(b+disc);
x=X(3)+z;
%Sort the entries of X to find the two closest to x
if abs(x-X(2))<abs(x-X(1))
Q=[X(2) X(1) X(3)];
X=Q;
Y=f(X);
end
if abs(x-X(3))<abs(x-X(2))
R=[X(1) X(3) X(2)];
X=R;
Y=f(X);
end
%Replace the entry of X that was farthest from x with x
X(3)=x;
Y(3) = f(X(3));
y=Y(3);
%Determine stopping criteria
err=abs(z);
relerr=err/(abs(x)+delta);
if (err<delta)||(relerr<delta)||(abs(y)<epsilon)
break
end
end
3 Kommentare
Walter Roberson
am 29 Sep. 2024
Exactly how have you defined f before calling
muller(f,1,1.5,2,0.001,0.001,10)
?
Akzeptierte Antwort
Walter Roberson
am 28 Sep. 2024
equation used is x^3+x^2-4x-4
X=[x0 x1 x2];
Y=f(X);
You are passing a vector of X values to f. You have coded x^3+x^2-4x-4 expecting scalar inputs x . x^3 is x*x*x where * is algebraic matrix multiplication. So you are trying to take [1 by 3] * [1 by 3] * [1 by 3] -- which is going to fail. Also, 4x is just invalid syntax in MATLAB: MATLAB has absolutely no implied multiplication.
Learn how to use the element-wise versions of operators -- x.^3 instead of x^3
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Calculus finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!