6

如果我有一個數組(長度未知,直到運行時),有沒有辦法用數組中的每個元素作爲單獨的參數調用函數?在Matlab中是否有一個splat運算符(或等效)?

像這樣:

foo = @(varargin) sum(cell2mat(varargin)); 
bar = [3,4,5]; 
foo(*bar) == foo(3,4,5) 

語境:我有指標到n -d陣列,Q列表。我想要的是類似Q(a,b,:),但我只有[a,b]。由於我不知道n,我不能只編寫索引。

回答

7

在MATLAB中沒有這樣做的操作符。然而,如果你的指標(即在你的例子bar)被存儲在cell array,那麼你可以這樣做:

bar = {3,4,5}; %# Cell array instead of standard array 
foo(bar{:});  %# Pass the contents of each cell as a separate argument 

{:}創建了一個從單元陣列comma-separated list。除了覆蓋existing operators之一(圖示爲herehere)之外,這可能是您在示例中以「操作員」形式獲得的最接近的內容,以便它從標準數組生成逗號分隔列表,或者創建您的自己的類來存儲你的索引,並定義現有的操作符是如何操作的(兩者都不適合心臟!)。

對於您的索引任意ND陣列的具體例子,你也可以從使用sub2ind功能(如詳細herehere)你的下標的指數計算線性指標,但比你會爲你最後可能會做更多的工作我上面用逗號分隔的列表解決方案。另一種選擇是compute the linear index yourself,它將回避converting to a cell array並且只使用矩陣/向量操作。這裏有一個例子:

% Precompute these somewhere: 
scale = cumprod(size(Q)).'; %' 
scale = [1; scale(1:end-1)]; 
shift = [0 ones(1, ndims(Q)-1)]; 

% Then compute a linear index like this: 
indices = [3 4 5]; 
linearIndex = (indices-shift)*scale; 
Q(linearIndex) % Equivalent to Q(3,4,5) 
相關問題