How do I create a local function using a string?

11 views (last 30 days)
Hello!
I am attempting to create a local function from a string. Essentially, I have a function handle that contains 10000 cosines (generated from Mathematica), and the calls to the anonymous function take way too long. To reduce this time, I would like to either create a function in another file that contains this long function, or create it within my script (at the bottom).
In other words, I want my code to look like this:
functionHandle = @(x,y,z) 1*cos(.5*x+y+z) + 2*cos(x + .3*y + z) + ... 10000*cos(x + 0.4*y + 0.2*z); %this is not true,
functionHandlestr = func2str(functionHandle);
function output = func(x,y,z)
output = functionHandlestr(x,y,z);
end
I know that this functionHandlestr will not work, but I am looking for some way to make that string into something that can accept x, y, and z.
Thanks,
Sam

Answers (1)

Star Strider
Star Strider on 22 Feb 2019
I am attempting to create a local function from a string.
Since you are starting from a string, use the str2func (link) function instead.
Try this:
str = '1*cos(.5*x+y+z) + 2*cos(x + .3*y + z)'
str = vectorize(str)
fcn = str2func(['@(x,y,z)' str])
testfcn = fcn(3,5,7)
produces:
testfcn =
1.5615301808159
  3 Comments
Star Strider
Star Strider on 22 Feb 2019
My pleasure.
With that constraint, I would create a ‘.m’ file function file. If you have the Symbolic Math Toolbox, you can import your function (copy-paste) and then use the matlabFunction (link) function to create a function file for your function (also see the documentation on Generate MATLAB Functions from Symbolic Expressions (link)), or use the vectorize (link) function on your imported string and create the function file yourself. This could be a multi-step process, although it would not be difficult in any event.
I know of no other truly automated way to do it.
Steven Lord
Steven Lord on 22 Feb 2019
Do you have or can you generate vectors of coefficients for the cos calls and the variables x, y, and z inside the cos calls? Rather than calling cos ten thousand times, depending on the sizes of the variables x, y, and z (scalar or not?) you may be able to call it once on a matrix of data and sum the results.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!