How to receive a function in MATLAB app DESIGNER given by user in edit field?

조회 수: 14 (최근 30일)
HI,
I am working on an app where user will put function and a value .output will be the value we get putting the input value in function.
such as, function will be
y=x^2+2^x+3
and x=2
how to code this??

채택된 답변

Voss
Voss 2022년 5월 6일
Something like this would work for functions of one variable, which is always called 'x'
% user inputs:
str = 'x^2+2^x+3'; % function, taken from an EditField
x = 2; % x value
f = str2func(['@(x)' str])
f = function_handle with value:
@(x)x^2+2^x+3
y = f(x) % output
y = 11
To be more general than that, you'd have to modify this approach or do something else.
  댓글 수: 3
Himalay  Baidya
Himalay Baidya 2022년 5월 7일
detailed code given below=-----function and a value is taken from user .and when button clicked the result shown in text field.
eq=app.EditField.Value;
x=app.EditField2.Value;
f = str2func(['@(x)' eq]);
y = f(x);
app.EditField3.Value=num2str(y);
Voss
Voss 2022년 5월 7일
You're welcome! Glad it's working.
The code you shared just now looks like it will work, assuming:
  • app.EditField is an EditField (i.e., a uieditfield of style 'text')
  • app.EditField2 is a NumericEditField (i.e., of style 'numeric' - if not, you can use str2double to convert x to a number), and
  • app.EditField3 is an EditField (again, of style 'text' - if not, you can avoid converting y to a string with num2str and use the numeric value of y directly).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Develop Apps Using App Designer에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by