3

I need to write a fixed point iteration algorithm and it's mostly coded but I'm running into this error:

Undefined function or variable 'g'.

I want to define g as g(x) = 1/2*(1+5/x). However, I'm a matlab n00b and unsure how to do this. Any help would be much appreciated, thanks.

  function [y,k] = fixedpoint(g,p0,tol,max1)
          for k=1:max1
          p = g(p0);
          err = abs(p-p0);
          abserr = abs(sqrt(5)-p);
          ratioerr = abserr/(abs(sqrt(5)-p0));

          if (err<tol)
             break
          end
          p0 = p;

  end
  if (k==max1)
      disp('The algorithm did not converge')
  end
  y = p;

1 Answer 1

3

You can define g as a anonymous function

g = @(x)1/2*(1+5/x)

Then call your function fixedpoint in usual way

Sign up to request clarification or add additional context in comments.

2 Comments

You can also pass the handle to a M file function by passing @funcname.
Be VEWY, VEWY careful following this advice. Note that the code P0W shows uses / not ./ so if called with vector or array input, it will produce totally unexpected results. Then you next anguished question will be to ask why your code does not work. Far better programming technique is to use ./ on things like this, even if you normally expect to pass it scalar input, because one day you won't do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.