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

19 vues (au cours des 30 derniers jours)
Eoghan Summers
Eoghan Summers le 9 Juil 2020
Commenté : Dennis le 9 Juil 2020
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 commentaires
Fangjun Jiang
Fangjun Jiang le 9 Juil 2020
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?
Eoghan Summers
Eoghan Summers le 9 Juil 2020
Yes, x is defined. The "val = x(1)^3 + x(2)^2" is passed to another function, for which values of x are input.

Connectez-vous pour commenter.

Réponses (2)

Fangjun Jiang
Fangjun Jiang le 9 Juil 2020
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

Arthur Roué
Arthur Roué le 9 Juil 2020
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 commentaires
Eoghan Summers
Eoghan Summers le 9 Juil 2020
Yes! That works perfectly, thank you very much
Dennis
Dennis le 9 Juil 2020
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings 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