从文件中的现有向量函数创建匿名标量函数

create anonymous scalar function from existing vector functions in file

我想创建一个匿名函数,它接受 Matlab 文件中现有向量函数的第一个输出变量。例如,单独的M文件中现有的向量函数是

function [y1,y2] = myfun(x1)
    y1 = x1;
    y2 = x1^2;
end

是否可以从 myfun() 创建一个取 y1 值的匿名标量函数?感谢您的任何建议。


P.S。我这样做是因为实际上我原来的功能更像是

function [y1,y2] = myfun(x1,x2)
    y1 = x1+x2;
    y2 = x1^2+x2^2;
end

我想创建一个只有一个参数 x1 的标量函数 y1(将已知值 x2 传递给匿名函数)。

我想我知道你在找什么,但有点不清楚。如果您从这样的函数开始:

function [y1,y2] = myfun(x1,x2)
  y1 = x1+x2;
  y2 = x1^2+x2^2;
end

您可以使用固定值 x2 来创建包装器匿名函数(在创建匿名函数时固定为任何变量),如下所示:

newFcn = @(x1) myfun(x1, x2);

现在,您可以使用它从 myfun 获得您想要的两个输出中的任何一个。例如:

y1 = newFcn(x1);        % Gets the first output
[~, y2] = newFcn(x1);   % Gets the second output
[y1, y2] = newFcn(x1);  % Gets both

根据@David的方法我调整了代码,效果很好。

function y = myfun(x1,x2)
    y1 = x1+x2;
    y2 = x1^2+x2^2;
    y = [y1 y2];
end

和匿名函数 output1 和 output2 return 分别是 y1 和 y2。

paren=@(y,varargin) y(varargin{:});
output1 = @(x1) paren(myfun(x1,x2), 1);
output2 = @(x1) paren(myfun(x1,x2), 2);