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

6 vues (au cours des 30 derniers jours)
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!

Réponses (2)

Walter Roberson
Walter Roberson le 20 Nov 2018
try
func(0)
catch
.... do appropriate rejection here
end
note: consider using vectorize()
  1 commentaire
Jan
Jan le 20 Nov 2018
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

Connectez-vous pour commenter.


Adam Danz
Adam Danz le 20 Nov 2018
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 commentaire
Adam Danz
Adam Danz le 20 Nov 2018
Modifié(e) : Adam Danz le 20 Nov 2018
This solution is an implementation of Walter's and Jan's suggestions which I only saw after submitting this solution.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by