Convert a string into a function of x

조회 수: 61 (최근 30일)
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2018년 11월 21일
편집: KRISHNA MAHTO 2023년 1월 12일
Hi all,
I have created a string like this:
Sstr = join(compose('(x(%d:%d)-x(%d:%d))))', A), ' + ')
so I get a result:
Sstr='(x(2:180)-x(1:179)+(x(182:360)-x(181:359))'
Is it possible to convert the string into a function of x like this??:
f=@(x) (x(2:180)-x(1:179)+(x(182:360)-x(181:359))
thanks
Nikolas
  댓글 수: 1
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2018년 11월 21일
Here is the code
A=[2 180 1 179 182 360 181 359];
str = join(compose('(x(%d:%d)-x(%d:%d))', A), ' + ')

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

채택된 답변

Stephen23
Stephen23 2018년 11월 21일
편집: Stephen23 2018년 11월 21일
You can use str2func:
fun = str2func(['@(x)',Sstr]);
and then call it just like any other function.
  댓글 수: 4
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2018년 11월 21일
Well I solved my problem by converting the cell to a character like this:
g = cell2mat(Sstr)
f = str2func(['@(x)' g])
thanks for the comments !
Stephen23
Stephen23 2018년 11월 21일
@Nikolas Spiliopoulos: you should check the contents of g to make sure that they make sense.
Don't forget to accept my answer if it helped you!

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

추가 답변 (1개)

KRISHNA MAHTO
KRISHNA MAHTO 2023년 1월 12일
편집: KRISHNA MAHTO 2023년 1월 12일
i have taken string as an input form the user ,, and want data to be converted into funtion of x and y , by the program itself ,,,for easy usage ,
%code to take input form the user -
prompt = "input U:-"
prompt = "input U:-"
u = input(prompt,"s")
Unable to run the 'fevalJSON' function because it calls the 'input' function, which is not supported for this product offering.
prompt = "input V:-"
v = input(prompt ,"s")

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by