一种可能的方式来做到这一点是将功能句柄保存到.mat
文件(使用-v7.3
标志,以便它创建了一个容易修改的HDF5文件),修改struct
包含工作空间数据的文件内对于匿名函数(使用内置于MATLAB中的HDF5工具),然后再次从文件加载匿名函数。
这里是一个小功能,这正是这么做的(和它的工作原理相对简单的变量类型)
function result = modifyfunc(f, varname, value)
% modifyfunc - Modify the workspace of an anonymous function
%
% INPUTS:
% f: Function Handle, Anonymous function to modify
% varname: String, Name of the variable to modify
% value: Data to replace the specified variable
% If the value is a struct, recursively modify the function handle
if isstruct(value)
fields = fieldnames(value);
result = f;
% Modify each field separately
for k = 1:numel(fields)
% Append the fieldname to the variable name and modify
name = [varname, '.', fields{k}];
result = modifyfunc(result, name, value.(fields{k}));
end
return;
end
% Write the anonymous function to an HDF5 file
fname = tempname;
save(fname, 'f', '-mat', '-v7.3');
% Replace any "." in the variable name with "/" to construct the HDF5 path
varname = strrep(varname, '.' , '/');
% Now modify the data in the file
h5write(fname, ['/#refs#/e/' varname], value);
% Load the modified function handle from the file
result = load(fname, '-mat');
result = result.f;
% Remove the temporary file
delete(fname);
end
而且你可以用它喜欢:
a = 1;
b = struct('field', 2);
f = @(x)disp(a + b.field + x);
f(10)
% 13
f2 = modifyfunc(f, 'a', 2);
f2(10)
% 14
f3 = modifyfunc(f2, 'b.field', 3);
f3(10)
% 15
b.field = 4;
f4 = modifyfunc(f3, 'b', b);
f4(10)
% 16
一些注意事项包括:
- 替换数据必须与原始数据大小相同
- 这依赖于.mat文件的格式,对于匿名函数完全没有记录,所以它可能会在将来的版本中失败。
- 目前,该功能工作区中的变量不适用于
cell
数组。
对于温和的附加安全边界,您可以将结构字段另存为一个mat文件(https://www.mathworks.com/help/matlab/matlab_env/save-load- and-delete-workspace-variables.html#bvdx_92-1)并重新加载。它仍然很脏,但仍然使用“功能”。 –