On MATLab app designer, how can i get an editfield text as a variable?

Hello, I have am developing a matlab app, where the app user inputs a function to an edit field, and i need to use whatever that function is in a later part of the code. The problem is that the editfield outputs as text rather than a variable/function. Does anyone know how can I output it as a variable?
The code is as follows:
So say user inputs to EditField: x(1)^3 + x(2)^2
Then I want to set: val = app.EditField.Value;
However, this gives me the text: val = 'x(1)^3 + x(2)^2'
When i want: val = x(1)^3 + x(2)^2
Is this possible? Thanks for the help.

2 Comments

Do you mean you have x defined,e.g. x=1:3, you want to Val=1^3+2^2=5?
or do you want val=f(x)=x(1)^3 + x(2)^2 as a function handle?
Yes, x is defined. The "val = x(1)^3 + x(2)^2" is passed to another function, for which values of x are input.

Sign in to comment.

Answers (2)

EditFieldText='x(1)^3 + x(2)^2';
F=str2func(['@(x)',EditFieldText]);
Then pass the function handle F to another function and use it. You don't have to worry about variable name x.
>> y=1:3
y =
1 2 3
>> F(y)
ans =
5
or you can pass EditFieldText over to the other function and construct the function handle there
If you want to evaluate an expression in a string, check for eval or evalin functions.
For instance :
x = [1 2];
str = 'x(1)^3 + x(2)^2';
val = eval(str);

2 Comments

Yes! That works perfectly, thank you very much
It might be worth to mention that this might cause problems down the road depending on your apps users. eval will evaluate any expression entered - including for example system commands.

Sign in to comment.

Categories

Find more on Create Custom UI Components in Help Center and File Exchange

Asked:

on 9 Jul 2020

Commented:

on 9 Jul 2020

Community Treasure Hunt

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

Start Hunting!