Create a function from user input string

2 ビュー (過去 30 日間)
Jared
Jared 2011 年 11 月 23 日
編集済み: Stephen23 2018 年 11 月 7 日
I am trying to develop a GUI which will allow the user to type a function into a text box and then perform operations to that function. For example suppose the user inputs 'x^2+2x+3' into a text box.
How can I convert the string into a function so I can perform iterative operations on?
such as:
function [y] = f(x)
y=x^2+2x+3;
end
I am fairly new at matlab so any help would be appreciated.

採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 11 月 23 日
>> str='x^2+2*x+3'
str =
x^2+2*x+3
>> f=inline(str)
f =
Inline function:
f(x) = x^2+2*x+3
>> f(2)
ans =
11
  2 件のコメント
klement omeri
klement omeri 2018 年 11 月 7 日
Is there any other way to do this? I am doing it in the same way but matlab shows me a yellow warning that inline function will be removed in a future release.
Stephen23
Stephen23 2018 年 11 月 7 日
編集済み: Stephen23 2018 年 11 月 7 日
@klement omeri: read the very first line of the inline help, which states "inline will be removed in a future release. Use Anonymous Functions instead." And then use an anonymous function, just like the documentation advises. For example (from the help):
>> str = '@(x)7*x-13';
>> fh = str2func(str);
>> fh(3)
ans =
8

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2011 年 11 月 23 日

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by