After requesting input of str2func, how do I make sure the user wrote a valid function?
6 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(2 个)
Walter Roberson
2018-11-20
try
func(0)
catch
.... do appropriate rejection here
end
note: consider using vectorize()
1 个评论
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
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!