问题
In Matlab, I have a function handle defined as a vector like this
F = @(x) [...
coeff1*x(1)*x(4); ...
coeff2*x(3); ...
coeff3*x(7)*x(3) ...
];
In reality it has 150 rows. I need to extract different subsets the functions in the rows. For example make a new handle from the rows 3:17
of those in F
. But I can't just go indexing a handle. Is there a solution?
Edit: I need the subset as a new handle, in other words I can not evaluate the entire F and just select the solution rows.
Thanks in advance.
回答1:
How about this:
F = @(x)[
5*x.^2*x*4;
6*x;
12*x.^2*x*3
];
newF = getFunHandles(F,2:3);
where getFunHandles
works for any arbitrary range, e.g. 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);
回答2:
It's a bit messier to create but it might make more sense to have a vector of function handles rather than a function handle that creates a vector:
F = {...
@(x)coeff1*x(1)*x(4); ...
@(x)coeff2*x(3); ...
@(x)coeff3*x(7)*x(3) ...
};
And now you can call
cellfun(@(x)x(y),F(3:17))
or even
F2 = @(y)cellfun(@(x)x(y),F(3:17))
And now you can call
y = rand(10,1)
F2(y)
And only get back rows 3
to 17
of your original F
. This is basically just wrapping up loops in shorthand. You need to make sure your input y
has the right size or you will get an error (i.e. if y
is [1,2]
and your line three tries to call y(7)
you will get an error)
回答3:
You can convert your original function to the format used in Dan's answer:
>> 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)
Now H
is a cell array containing the function handles and you can index into that.
来源:https://stackoverflow.com/questions/36279499/how-to-obtain-a-subset-of-functions-from-a-function-handle-that-is-a-vector-of-f