2013-06-05 42 views
0

有沒有一種方法來概括以下內容? (注:nargout_requested可以不除已知在運行時在matlab中調用一個函數,並讓調用者在運行時確定輸出參數的數量

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}; 
     ... 

換句話說,我想調用具有變元的單元陣列的功能,以及分配功能的輸出到單元陣列,並請求一定數量的輸出參數。

在蟒蛇,這將僅僅是:

outputs = f(*args) 

但Matlab要求你,告訴你多少個參數要你調用之前的函數,如果你有太多的輸出參數給你一個錯誤。

回答

2

啊哈,我想我有。我仍然有特殊情況的輸出的數量爲零,非零之間:

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{:}); 
+0

我想你也可以避免傳遞'nargout_requsted'並使用內置的['nargout'](http://www.mathworks.com/help/matlab/ref/) nargout.html)而不是 – Will

+0

也許我沒有在我的問題中說清楚:我有理由手動指定我想要的參數數量。這是用於測試用具。 –

+1

'apply_and_gather'函數的作用是破壞MATLAB的正常多重參數方法,並將結果作爲單元格數組返回。 'apply_and_gather'的'nargout'值始終爲1. –

0

要調用另一個函數,請求可變數量的輸出,使用一些不常見的語法魔術,像這樣:

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

要返回可變數量的參數,請查看varargout。你的代碼看起來像這樣:

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

    % ... your code here, setting values to the varargout cell 
+0

不,我不想返回多個輸出;我想返回一個單元陣列的單個輸出,它的元素是函數I調用的k個輸出,其中k只在運行時才被知道。 –

+0

我曲解了。查看更新。 – Pursuit

+0

是的,我想到了這一點(使用'[somevar {:}]')。不過,你必須特殊情況下使用0個參數。 (請參閱我的回答) –

相關問題