MATLAB Answers

Convert a string into a function of x

63 views (last 30 days)
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 Comment
Nikolas Spiliopoulos
Nikolas Spiliopoulos on 21 Nov 2018
Here is the code
A=[2 180 1 179 182 360 181 359];
str = join(compose('(x(%d:%d)-x(%d:%d))', A), ' + ')

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 21 Nov 2018
Edited: Stephen Cobeldick on 21 Nov 2018
You can use str2func:
fun = str2func(['@(x)',Sstr]);
and then call it just like any other function.
  4 Comments
Stephen Cobeldick
Stephen Cobeldick on 21 Nov 2018
@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!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!