Search code examples
matlabfunctionindexinghandle

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


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.


Solution

  • 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);