Values in function handle (this worked for inline...)

I want to create sets of random linear functions: m*x+b for many different m values and b values. I used to do something like this:
s = sprintf('%d*x+%d',randi(10), randi(3))
f = inline(s)
and I'd end up with an f nicely defined in terms of my random variables (f = 8x+2). Then I can plot and/or evaluate this function for any x.
How do I do something similar with function handles? I have tried doing:
F = @(x) s;
but it appears that it substitutes s in and doesn't understand x is an argument (so F(1) = 8*x+2, not 8*1+2).
I obviously do NOT want to create a brand new function file (which is why I want inline functions in the first place).
Anyone have any ideas?
Regards,
Dr. Dostert

 採用された回答

Star Strider
Star Strider 2014 年 6 月 12 日

0 投票

% Preferred:
F = @(b,x) b(1).*x + b(2);
% Less preferred:
F = @(m,b,x) m.*x + b;
The first is preferred because you can use it in a nonlinear or other solver if you so choose. It also has both parameters as a single vector ‘b’, making it easier to program.
The second is a bit more intuitive (individual parameters, not a vector of parameters), but doesn’t have the flexibility of the first.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeFunction Creation についてさらに検索

質問済み:

2014 年 6 月 12 日

回答済み:

2014 年 6 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by