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 日

2 投票

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 get an error like this
Undefined function 'str2func' for input arguments of type 'cell'.
Maybe it's my matlab version it's 2017a.
is there any other option?
thanks
Stephen23
Stephen23 2018 年 11 月 21 日
編集済み: Stephen23 2018 年 11 月 21 日
"Maybe it's my matlab version it's 2017a."
You wrote in your question "so I get a result:"
Sstr='(x(2:180)-x(1:179)+(x(182:360)-x(181:359))'
But it turns out that you actually have a cell array of character vectors, not a single character vector like you showed us. How do you expect to convert a cell array of character vectors to one function? Answer: you need to actually convert that cell array of character vectors into one character vector, just like you showed in your question.
"is there any other option?"
To do what? Convert a string to a function? No, not really. To convert your array A to a function? Quite possibly.
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 日

0 投票

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")

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by