內置函數bsxfun
是一個應該能夠幫助的快速實用程序。它被設計爲針對具有不匹配尺寸的兩個輸入以每個元素爲基礎執行2個輸入功能。單身人士尺寸被擴大,並且非單身人士尺寸需要匹配。 (這聽起來令人困惑,但一旦grok'd在很多方面有用)。
正如我理解你的問題,你可以調整每個向量的維度形狀來定義它應該定義的維度。然後使用嵌套的bsxfun
調用來執行乘法。
實施例的代碼如下:
%Some inputs, N-by-1 vectors
x = [1; 3; 9];
y = [1; 2; 4];
z = [1; 5];
%The computation you describe, using nested BSXFUN calls
bsxfun(@times, bsxfun(@times, ... %Nested BSX fun calls, 1 per dimension
x, ... % First argument, in dimension 1
permute(y,2:-1:1)) , ... % Second argument, permuited to dimension 2
permute(z,3:-1:1)) % Third argument, permuted to dimension 3
%Result
% ans(:,:,1) =
% 1 2 4
% 3 6 12
% 9 18 36
% ans(:,:,2) =
% 5 10 20
% 15 30 60
% 45 90 180
爲了處理尺寸的任意數量,這可以通過使用一個遞歸或循環結構進行擴展。循環看起來是這樣的:
allInputs = {[1; 3; 9], [1; 2; 4], [1; 5]};
accumulatedResult = allInputs {1};
for ix = 2:length(allInputs)
accumulatedResult = bsxfun(@times, ...
accumulatedResult, ...
permute(allInputs{ix},ix:-1:1));
end
啊,我現在看到你的編輯關於不知道維數。我會更新我的答案。 – Nigel