0

以下を一般化する方法はありますか?(注:nargout_requested実行時以外はわからない場合があります

function outputs = apply_and_gather(f, args, nargout_requested)
  switch nargout_requested
    case 0
      f(args{:});
      outputs = {};
    case 1
      o1 = f(args{:});
      outputs = {o1};
    case 2
      [o1,o2] = f(args{:});
      outputs = {o1,o2};
    case 3
      [o1,o2,o3] = f(args{:});
      outputs = {o1,o2,o3};
      ...

つまり、引数のセル配列を使用して関数を呼び出し、関数の出力をセル配列に割り当て、特定の数の出力引数を要求したいと考えています。

Python では、これは次のようになります。

outputs = f(*args)

しかし、Matlab では、関数を呼び出す前に必要な引数の数を関数に伝える必要があり、出力引数が多すぎるとエラーが発生します。

4

2 に答える 2

2

ああ、私はそれを持っていると思います。出力数を 0 と 0 以外の間で特殊なケースにする必要があります。

function outputs = apply_and_gather(f, args, nargout_requested)
switch nargout_requested
    case 0
        f(args{:});
        outputs = {};
    otherwise
        outputs = cell(1, nargout_requested);
        [outputs{:}] = f(args{:});
end

使用例:

>> outputs=apply_and_gather(@polyfit,{[0:0.1:1 1.1],[0:0.1:1 1],3},3)

outputs = 

    [1x4 double]    [1x1 struct]    [2x1 double]

出力引数がゼロの特殊なケースを使用しない場合、次のようになります。

>> outputs=apply_and_gather2(@polyfit,{[0:0.1:1 1.1],[0:0.1:1 1],3},0)
The left hand side is initialized and has an empty range of indices.
However, the right hand side returned one or more results.

Error in apply_and_gather2 (line 3)
    [outputs{:}] = f(args{:});
于 2013-06-05T00:51:14.970 に答える
0

To call another function, requesting a variable number of outputs, use some non-obvious syntax magic, like this:

function outputs=  = apply_and_gather(f, args, nargout_requested)
    outputs= cell(1, requested);  %Preallocate to define size
    [outputs{:}] = f(args{:});

To return a variable number of arguments, look into varargout. Your code would look like this:

function varargout =  = apply_and_gather(f, args, nargout_requested)
    varargout = cell(1, requested);

    % ... your code here, setting values to the varargout cell
于 2013-06-05T01:02:00.100 に答える