Check if a function handle is valid
古いコメントを表示
I use str2fun(...) to create a function handle from a user-inputted string. I want to be able to run a check to make sure the function created is valid and no typos were made. I could not find a way to do this. Any suggestions?
Thanks, Ryan
MATLAB R2014a
1 件のコメント
Steven Lord
2021 年 2 月 26 日
What is a "valid" function handle?
f = @quit; % NOTE: Don't execute f if you have data in your MATLAB session you need!
f is a "valid" function handle in that it won't error when called. But you may not want users to enter 'quit' as the user-inputted string and blindly evaluate that function handle -- the "Bobby Tables" scenario.
g = @() zeros(1:12); % MAY error or MAY succeed and take a LONG time doing so
This may successfully execute (though it may take a while) or may throw an error depending on your computer's memory availability and your MATLAB settings. Is it "valid"?
採用された回答
その他の回答 (3 件)
Sean de Wolski
2014 年 7 月 1 日
try
fun()
catch
disp 'didn''t work'
end
Try it and catch failures. Or provide a listbox with known functions to remove the human typing element.
Ryan
2014 年 7 月 1 日
0 投票
1 件のコメント
Sean de Wolski
2014 年 7 月 1 日
Well if you catch the MException, you could look at the message of it.
...
catch ME
ME.message
end
Jos (10584)
2014 年 9 月 19 日
0 投票
カテゴリ
ヘルプ センター および File Exchange で Scope Variables and Generate Names についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!