How to solve an operation written on a EditField?

1 view (last 30 days)
I am new to Matlab, I have been using it to do some math. I created a very easy program with App Designer, the idea is that the user can enter almost any expression and then display the result, for example "7 + 4" or "4x + 2 = 0". The problem is, I don't know how to "convert" the text from the EditField to a mathematical expression. I did a little test with "2 + 4" using the "str2sym ()" function and the "num2str ()" function, but when setting the result in the other EditField, it shows me this error: Error using num2str (line 47) Input to num2str must be numeric.
methods (Access = private)
% Button pushed function: CalculateButton
function CalculateButtonPushed(app, event)
expr = str2sym(app.ExpressionEditField.Value);
app.ResultEditField.Value = num2str(expr);
end
end
I don't know what to do, any recommendation is appreciated.

Accepted Answer

Walter Roberson
Walter Roberson on 22 Aug 2021
The result of str2sym() is symbolic. num2str() cannot convert symbolic to string.
Instead of using num2str(expr) you can use string(expr)
Note: the expression to be converted must be valid MATLAB syntax. "4x + 2 = 0" is not valid MATLAB syntax. The user would have had to have entered "4*x + 2 == 0", or else you would have to have processed what the user did enter in order to make it into valid MATLAB syntax.
MATLAB does not have any implied multiplication -- no "4x" as meaning to multiply x by 4. Not anywhere that I can find.
  3 Comments
Walter Roberson
Walter Roberson on 22 Aug 2021
Use subs(), like
syms x
y = 4 * x + 2
y = 
subs(y, x, 2)
ans = 
10

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!