假设与模型 1 关联的方法总是一起使用,而不是与模型 2 或 3 的方法混合使用,那么您可以在一个文件中设置具有一个模型的所有函数的代码:
% MODEL1 Methods that implement model 1
function [boundary_left,boundary_right,flux,source] = model1
boundary_left = @boundary_left_method;
boundary_right = @boundary_right_method;
flux = @flux_method;
source = @source_method;
function [out, args] = boundary_left_method(input, args)
% [implementation]
end
function [out, args] = boundary_right_method(input, args)
% [implementation]
end
function [out, args] = flux_method(input, args)
% [implementation]
end
function [out, args] = source_method(input, args)
% [implementation]
end
end
基本上,这里有一个函数,它将句柄返回给实现一个方法的一组函数。boundary_left_method
是一个私有函数,因此不能直接访问,但model1
可以返回这些函数的句柄,这使得它们可以访问。
您现在可以执行以下操作:
[boundary_left,boundary_right,flux,source] = model1;
Solution = numerical_scheme_1(boundary_left,boundary_right,flux,source,parameters);
此解决方案与 OP 建议的自定义类解决方案非常相似,但更简单一些。我认为性能不会有很大差异,但唯一确定的方法是实施和计时各种选项。随着 MATLAB 的 JIT 改进,随着时间的推移,最有效的变化是什么。
请注意,此处提出的方案还允许将数据 ( parameters
) 包含在这些函数中:
% MODEL1 Methods that implement model 1
function [boundary_left,boundary_right,flux,source] = model1(parameters)
boundary_left = @boundary_left_method;
boundary_right = @boundary_right_method;
flux = @flux_method;
source = @source_method;
function [out, args] = boundary_left_method(input, args)
out = input * parameters; % You can use PARAMETERS here, note that it is not
% an input argument to this nested function, it is
% found in the parent scope.
end
% ...
end % This end here is important now, this way `boundary_left_method` is an
% nested function, not simply a separate function within the same file.
现在返回的函数句柄中嵌入boundary_left
了 的数据。parameters
请参阅相关文档。
如果您还控制采用这些函数句柄的数值方案函数的代码,您可以编写method1
et al. 改为返回句柄元胞数组,以及numerical_scheme_1
等。函数来获取句柄的元胞数组。然后你可以简单地做:
numerical_scheme_1(method1,parameters);
numerical_scheme_1(method2,parameters);
numerical_scheme_1(method3,parameters);
numerical_scheme_2(method1,parameters);
numerical_scheme_2(method2,parameters);
numerical_scheme_2(method3,parameters);
% etc.
然后,您可以使用循环遍历所有组合:
schemes = {@numerical_scheme_1, @numerical_scheme_2, ... };
methods = {method1, method2, method3, ... };
for ii=1:numel(schemes)
for jj=1:numel(methods)
schemes{ii}(methods{jj},parameters);
end
end
[免责声明:此代码未经测试,但我不明白为什么它不起作用......]