如何从函数句柄中获取函数子集,函数句柄是 Matlab 中的函数向量

How to obtain a subset of functions from a function handle that is a vector of functions in Matlab

在 Matlab 中,我有一个定义为向量的函数句柄,如下所示

F = @(x) [... 
coeff1*x(1)*x(4); ...
coeff2*x(3); ... 
coeff3*x(7)*x(3) ...
];

实际上它有 150 行。我需要提取行中函数的不同子集。例如,从 F 中的 3:17 行创建一个新句柄。但我不能只是去索引句柄。有解决办法吗?

编辑:我需要子集作为新句柄,换句话说,我无法评估整个 F 而只是 select 解决方案行。

提前致谢。

创建起来有点麻烦,但使用函数句柄向量而不是创建向量的函数句柄可能更有意义:

F = {... 
     @(x)coeff1*x(1)*x(4); ...
     @(x)coeff2*x(3); ... 
     @(x)coeff3*x(7)*x(3) ...
    };

现在您可以打电话给

cellfun(@(x)x(y),F(3:17))

甚至

F2 = @(y)cellfun(@(x)x(y),F(3:17))

现在您可以打电话给

y = rand(10,1)
F2(y)

并且只返回原始 F317 行。这基本上只是在 shorthand 中结束循环。您需要确保输入 y 的大小正确,否则会出现错误(即,如果 y[1,2] 并且您的第三行尝试调用 y(7) 您将得到一个错误)

您可以将您的原始函数转换为 Dan 的回答中使用的格式:

>> G=regexp(func2str(F), ';|\[|\]', 'split')
G = 
    '@(x)'    'coeff1*x(1)*x(4)'    'coeff2*x(3)'    'coeff3*x(7)*x(3)'    ''
>> H=cellfun(@str2func, strcat(G{1}, G(2:end-1)), 'uni', 0)
H = 
    @(x)coeff1*x(1)*x(4)    @(x)coeff2*x(3)    @(x)coeff3*x(7)*x(3)

现在 H 是一个包含函数句柄的元胞数组,您可以对其进行索引。

这个怎么样:

F = @(x)[
     5*x.^2*x*4;
     6*x; 
     12*x.^2*x*3
    ];

newF = getFunHandles(F,2:3);

其中 getFunHandles 适用于任意范围,例如3:17

function f = getFunHandles(F, range)
funStr = textscan(func2str(F),'%s','delimiter',';');
funStr = regexprep(funStr{1}, {'@(x)[', ']'}, {'', ''});
newFunStr = strcat('@(x)[',strjoin(funStr(range),';'),']');
f = str2func(newFunStr);