# How to use input string as a function in Appdesign?

조회 수: 3 (최근 30일)
Abrar 2023년 2월 21일
댓글: Abrar 2023년 2월 21일
I am beginner in appdesigning. However, I am trying here to make an interface where user will write down the equation of a function and the value of the variable. After clicking the button,he will get the value of f(x) for the given value. Maybe I have some errors in the codes for which,after giving datas and clicking then,there seems something wrong. Someone please help me to debug this I need that emergency.

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

### 채택된 답변

Simon Chan 2023년 2월 21일
편집: Simon Chan 2023년 2월 21일
In case you would like to use function str2func, the string in the editfield for entering the equation should looks like the following:
@(x)x^2
x^2
and use the following inside the callback
f = str2func(s)
f = @(x)(str2func(s))
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Abrar 2023년 2월 21일
Awwwww it worked. Thanks a loooot <3

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

### 추가 답변 (1개)

Steven Lord 2023년 2월 21일
If the user enters an expression in the edit field, you can convert it into an anonymous function using a couple of functions.
s = 'x^2+y';
Make it so it can be called with a vector of values using the vectorize function.
vecFunction = vectorize(s)
vecFunction = 'x.^2+y'
Get the list of variables using symvar.
vars = symvar(s)
vars = 2×1 cell array
{'x'} {'y'}
Assemble the string representation of the anonymous function, joining the list of variables and the function that was entered into the edit box.
str = "@(" + join(vars, ", ") + ") " + vecFunction
str = "@(x, y) x.^2+y"
Make the anonymous function with str2func.
f = str2func(str)
f = function_handle with value:
@(x,y)x.^2+y
To check let's call the function handle.
z = f(1:10, 100)
z = 1×10
101 104 109 116 125 136 149 164 181 200

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

### 카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by