How do I create a local function using a string?

11 次查看(过去 30 天)
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

回答(1 个)

Star Strider
Star Strider 2019-2-22
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 个评论
Star Strider
Star Strider 2019-2-22
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 2019-2-22
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by