After requesting input of str2func, how do I make sure the user wrote a valid function?

3 ビュー (過去 30 日間)
Santiago Oliveira
Santiago Oliveira 2018 年 11 月 20 日
編集済み: Adam Danz 2018 年 11 月 20 日
I have a part of a script that requires the user to type a function, which needs to be only dependant of x. something like sin(x), or cos(2*x), or x^2+1, or etc. I have used:
func=str2func(['@(x)' input('Please, write f(x):','s')]);
Now, if the user writes: c^2, or c+2, or abcdef, it gives me a red error message. I really want it to give an error message saying something like:
"The function you wrote is invalid. Repeat."
"Please, write f(x):"
allowing the user to write a correct function of x.
Thank you!

回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 11 月 20 日
try
func(0)
catch
.... do appropriate rejection here
end
note: consider using vectorize()
  1 件のコメント
Jan
Jan 2018 年 11 月 20 日
Or with the loop:
ready = false;
while ~ready
func = str2func(['@(x)', input('Please, write f(x):','s')]);
try
func(0);
ready = true;
catch ME
fprintf('Function rejected. Please, write f(x):\n');
end
end

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


Adam Danz
Adam Danz 2018 年 11 月 20 日
The solution below uses a try/catch statement nested within a while loop that tests the function. If the function passes, the while loop ends. If the function fails, 1) a message appears indicating why it failed and 2) the user is propted to try again. I also include a maximum number of failures (5) before the code gives up on the user and quits.
One word of caution, to test if the function works, I'm using the input value of 1. In the unlikely event that this input breaks the user's function, you could either replace that as the test value or build in a 2nd test in the 'catch' section.
errorCount = 0;
confirmed = false;
while ~confirmed
func=str2func(['@(x)' input('Please, write f(x):','s')]);
try
func(1);
confirmed = true;
catch ME
% If the user makes 5 mistakes in a row, quit and throw error
errorCount = errorCount + 1;
fprintf('The function you wrote is invalid: %s\n', ME.message)
if errorCount >= 5
rethrow(ME)
end
end
end
  1 件のコメント
Adam Danz
Adam Danz 2018 年 11 月 20 日
編集済み: Adam Danz 2018 年 11 月 20 日
This solution is an implementation of Walter's and Jan's suggestions which I only saw after submitting this solution.

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

カテゴリ

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