# (Should be) Simple function declarations in Matlab

1. Aug 3, 2008

### villiami

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. Aug 3, 2008

### rootX

try using

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

a =

5

>> eval(f)

ans =

x+1

3. Aug 3, 2008

### villiami

Thanks for that, but it still doesn't let me type something like:
f(2)

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?

4. Aug 3, 2008

### shoehorn

Pretty much this precise problem is solved by carefully reading the output of

Code (Text):
doc fminsearch

5. Aug 4, 2008

### rootX

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 =

x^2+x-31

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

diff_f =

2*x+1

>> solve(diff_f)

ans =

-1/2