How do I create a local function using a string?
조회 수: 3 (최근 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
댓글 수: 0
답변 (1개)
Star Strider
2019년 2월 22일
‘I am attempting to create a local function from a string.’
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
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
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 Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!