(Should be) Simple function declarations in Matlab

  • Context: MATLAB 
  • Thread starter Thread starter villiami
  • Start date Start date
  • Tags Tags
    Function Matlab
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 10K views
villiami
Messages
27
Reaction score
0
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)
 
Physics news on Phys.org
try using

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

a =

5

>> eval(f)

ans =

x+1
 
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?
 
villiami said:
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)

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

Code:
doc fminsearch
 
villiami said:
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?

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