Checking a simple equation for validity in MATLAB

I’ve got a MATLAB program that basically displays a simple four-function calculator (+, -, *, and /). The user enters the equation they want to solve, and it displays as they are pushing the buttons, and doesn’t evaluate until they finally hit the ‘=’ key. (The equation they enter is stored as a string, then I use the eval(equation) function to do this.)

I have to check to make sure they both don’t divide by zero, and that they enter a valid equation. The divide by zero part was easy, I just did a search for ‘/0’ and display an error message if it’s found in their equation.

But I have no idea how to check to make sure it’s valid. By this I mean I have to make sure they didn’t enter something like “6**9” or “/8+7”, etc…

I thought I could just do something like:


if eval(equation)
    %do stuff
else
    %give error message

But if the eval is invalid, rather than return an empty vector, like I thought it did, it produces an internal MATLAB error and the program ends.

I’m quite stumped…

You can use a try/catch block, like



try
  A = eval(stuff);
catch
  A = '';
end


By the way, MATLAB will happily divide by zero and give Inf as result.

Thanks!

Although the following types of equations still go through:
“5++8”
“+8”
etc…it just reads the first one as a straight plus sign, and the second as just a regular 8…which I guess isn’t bad, but I’d prefer it to catch that…but if it’s not possible, then that’s ok.

The second plus is being interpreted as a unary operator, just like -. It probably won’t like 5+++8, although I would not be horribly shocked if it did.

Well, the try/catch only makes sure that the string is a valid Matlab expression, but it can be anything, even the most complex and convoluted stuff. If you want to make sure that the string strictly follows the form ‘a OPERATOR b =’, I believe you’ll have to loop through all characters and check manually. Test whether the first one or more characters are digits (those have an integer value between 48 and 57), the first one that is not a digit is one of your operators, then again one or more digits, then the equal sign. And allow spaces between all of them if you feel like it.