Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

(Should be) Simple function declarations in Matlab

  1. Aug 3, 2008 #1
    I have already declared some variable values as (for example):
    a = 2
    b = 3

    Now I want to declare a function like:
    f(x) = x + a - b
    I will be optimizing w.r.t. x later, so I don't want to enter it as f(x,a,b)
    (or is it possible to oiptimise w.r.t. just one of the variables?)

    I tried
    f = inline('x+a-b','x')
    but then when I tried to evaluate it, it didn't have values for a and b (even though they were declared before!), so caused an error.

    Any ideas? (other than defining the function with a and b replaced by value, because this won't allow me to change a and b later)
  2. jcsd
  3. Aug 3, 2008 #2
    try using

    >> syms x,syms a,syms b;
    >> f = x-a+b;
    >> a = 5, b=6;

    a =


    >> eval(f)

    ans =

  4. Aug 3, 2008 #3
    Thanks for that, but it still doesn't let me type something like:

    which is what I need for the optimization (where I will enter fminsearch(@f,[0]) to find the minimizing x-value given the constant a and b values)

    Any ideas?
  5. Aug 3, 2008 #4
    Pretty much this precise problem is solved by carefully reading the output of

    Code (Text):
    doc fminsearch
  6. Aug 4, 2008 #5
    I most work with variables, I use following method for optimization:

    %continuing from that code ...
    >> f = x^2+x+a-b^2 %declaring f again to get some good differentiated function

    f =


    >> diff_f = diff(eval(f),x)

    diff_f =


    >> solve(diff_f)

    ans =

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: (Should be) Simple function declarations in Matlab
  1. MATLAB function (Replies: 2)

  2. Matlab function (Replies: 1)

  3. Matlab functions (Replies: 0)

  4. Matlab functions (Replies: 0)

  5. MATLAB function (Replies: 1)