How to put a function definition into a string?

10 ビュー (過去 30 日間)
Mr M.
Mr M. 2017 年 12 月 19 日
コメント済み: Walter Roberson 2017 年 12 月 19 日
I have a script, and I have an in-line function definition, for example like this:
f = @(a,x) 1./(1+exp(-tan(a).*(x-a)));
I want to write this function out into a text file, or a string variable. So I need
mystring = '1./(1+exp(-tan(a).*(x-a)))'
or
'@(a,x) 1./(1+exp(-tan(a).*(x-a)))'

採用された回答

Walter Roberson
Walter Roberson 2017 年 12 月 19 日
f = @(a,x) 1./(1+exp(-tan(a).*(x-a)));
mystring = char(f)
  2 件のコメント
Mr M.
Mr M. 2017 年 12 月 19 日
Thanks, and whatif I have the name of a function in a string like 'f', and I want to pass this name into char(), so I need char(f), but I have only mystring = 'f'?
Walter Roberson
Walter Roberson 2017 年 12 月 19 日
Then you avoid doing that.
Two approaches:
1) Store all of the handles as fields of a struct. When you get the name such as 'f', use dynamic field names to pull out the content. For this to work, the identifiers must be valid MATLAB variable names:
appropriate_handle = MyStruct.(mystring)
2) Store all of the handles in a cell array, and have another cell array of their corresponding identifiers (which would not have to be valid MATLAB identifier names). When the user selects from one of the identifiers, locate it in the list of identifiers and use the corresponding position to access the content of the cell array:
which_one = input('Which function name do you want?', 's');
[tf, idx] = ismember(which_one, list_of_names);
if tf
appropriate_handle = cell_of_handles{idx};
else
error('That was not a name')
end
or
idx = get(handles.list_of_functions, 'value')
if isempty(idx)
error('You must select an entry from the list')
end
appropriate_handle = cell_of_handles{idx};

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

その他の回答 (0 件)

カテゴリ

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