Problem Using User Input with Function Handle

3 ビュー (過去 30 日間)
Carl
Carl 2012 年 9 月 15 日
I am attempting to write a very short program that will requests a simple function of x and then take the numerical approximation of the function using quadv(). I am having a simple problem with not having the variable of the function declared before it is received from the user input. I'm sure this is a simple problem that I can't see because I am simply not that good with matlab.
g = input('Request a Function of (x): ');
f = @(x) g
Q = quadv(f,0,pi)
I know this program would work if 'g' was simply defined inside the code as being something like sin(x), cos(x), and so on but I cannot figure a way to get user input to work with this short piece of code.
Any help with this would be greatly appreciated.

採用された回答

Matt Fig
Matt Fig 2012 年 9 月 15 日
編集済み: Matt Fig 2012 年 9 月 15 日
If you are writing a function, it is probably best to dispense with input prompts and let the user pass in a function handle like most other functions. But,
>> g = vectorize(inline(input('Request a Function of (x): ','s')));
Request a Function of (x): sin(x)
>> quadl(g,0,pi/2)
ans =
1.0000
  1 件のコメント
Carl
Carl 2012 年 9 月 15 日
Thank you so much that works perfectly.

サインインしてコメントする。

その他の回答 (1 件)

Wayne King
Wayne King 2012 年 9 月 15 日
編集済み: Wayne King 2012 年 9 月 15 日
One thing you can use is str2func
g = input('Request a Function of (x): ','s');
% assume user inputs cos
f = str2func(g);
Q = quad(f,0,pi);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by