Coding a function to find zeros using a variant of the bisection/secant method

2 vues (au cours des 30 derniers jours)
Hello, I have a programming assignment where I have to implement a matlab function that is a variant of the bisection and secant method. Please see attachment for exact details. I am having problems with the code. Will someone help me with the necessary fixes? My code is as follows: —————————————————————————————————————-
if true
% code
function p = bisection(f, a, b, tol)
w=1;
for i=1:100
p= a +(w*f(a)*(a-b)/f(b)-w*f(a));
fprintf(a,b,p,f(p));
if f(p)*f(b)>0
w=0.5;
else
w=1;
a=b;
end
b=p;
if abs(b-a)<tol
abs(f(p))<tol
break;
end
end.

Réponse acceptée

Walter Roberson
Walter Roberson le 28 Sep 2021
No, no error about needing to use () . However,
output = bisection(@(x) sin(x)+3*cos(x).^2, -pi/2, pi/2, 1e-5)
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.

Error in solution>bisection (line 7)
fprintf(a,b,p,f(p));
function p = bisection(f, a, b, tol)
w=1;
for i=1:100
p= a +(w*f(a)*(a-b)/f(b)-w*f(a));
fprintf(a,b,p,f(p));
if f(p)*f(b)>0
w=0.5;
else
w=1;
a=b;
end
b=p;
if abs(b-a)<tol
abs(f(p))<tol
break;
end
end
end
This is because the first parameter to fprintf must be one of:
  1. A file identifier
  2. A format character vector or format string scalar
  3. A device object for some kinds of devices such as serialport objects
The first parameter you are passing is a, which is numeric but is not a valid file identifier.
  6 commentaires
Lavorizia Vaughn
Lavorizia Vaughn le 29 Sep 2021
Yeah dude, I’m still kind of lost. You mind telling me exactly what to change?
Walter Roberson
Walter Roberson le 29 Sep 2021
fprintf('Lovorizia, the value for a was %g .\nAnd b was %g .\n, Then there was p, which was %g .\n And lastly, if you still care, f(p) was %g .\n', a, b, p, f(p));

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Manage Products dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by