【发布时间】:2012-03-06 08:13:25
【问题描述】:
我想要一个函数(例如 fit 函数)返回一个匿名函数(通常存储在 struct 中),我可以保存并在以后使用。但是,传递@func 往往会传递函数指针而不是函数本身。 inline 函数是唯一的方法吗?我想避免inline,因为它非常慢。
如果这个问题不清楚,这里有一个有问题的代码示例:我在一些PATH 中写了一个testFunc.m 文件
%testFunc.m
function myfunc = testFunc()
myfunc = @(x) x.^2;
end
然后我将函数存储在struct 中。 (我知道这真的应该是一个对象!)
>> mystruct = struct;
>> mystruct.func = testFunc()
>> mstruct.x = [1 2 3];
>> save('myfile.mat','mystruct')
>> mystruct.func(mystruct.x)
ans =
1 4 9
如果我随后移动myfile.mat 或testFunc.m 并加载myfile.mat,我将无法加载旧结构。相反,我得到了错误:
>> cd 'otherdir'
>> load('../myfile.mat')
Warning: Could not find appropriate function on path
loading function handle PATH/testFunc.m>@(x)x.^2
我知道有问题,因为如果我检查functions
>> functions(mystruct.func)
ans =
function: '@(x)x.^2'
type: 'anonymous'
file: 'PATH/testFunc.m'
workspace: {2x1 cell}
有什么方法可以去除文件工作区信息吗? inline 函数是唯一的解决方案吗?
【问题讨论】:
-
我想我更明白这一点——感谢大家的讨论!目前,我正在使用内联函数,即使它们很慢: %testFunc.m function myfunc = testFunc() myfunc = inline('x.^2');结束
-
啊 - 如果您只需要可以表示为内联的函数,我认为您可以使用来自公共、干净工作区的“已清理”匿名函数作为
inline()的直接替代品并避免放缓;查看我的更新答案。 -
另外,如果您还没有,您可以使用 addpath() 来管理您的路径。这使您可以将源代码保留在 Matlab 路径中,而不管您当前的目录是什么。