簡體   English   中英

制作3D數組MATLAB

[英]Making a 3d array MATLAB

在MATLAB中

[Z,S]=meshgrid(0.01:0.01:1)

我還有一個名為X的100000x2矩陣,每一行都有兩組數據-p是第一列,x是第二列。

我想計算j索引行的exp ^(-S * X(j,2))。(* Z. ^ X(j,1))。 結果應為100x100x100000矩陣。 然后將沿第3維求平均值,並生成網格圖。 我嘗試過使用for循環

[Z,S]=meshgrid(0.01:0.01:1)
for j=1:100000
phi(j)=exp^(-S.*X(j,2)).*(Z.^X(j,1))
end

產生我需要的100x100x100000陣列。 但這給我錯誤

In an assignment  A(I) = B, the number of elements in B and I must be the same.
Error in phi (line 4)
phi(j)=exp(-S.*X(j,2)).*(Z.^X(j,1));

我不確定為什么會這樣嗎? 誰能找到一種更好的方法來嘗試找到我想要的結果? 因為我猜測可能存在完全矢量化的解決方案(或至少使用for循環)?

假設您要使用兩個以上的嵌套循環來獲取ZS ,因此該代碼總共將具有三個嵌套循環。

現在,矢量化技術在像這樣的可矢量化嵌套循環的情況下沒有改變-分別處理涉及不同迭代器的代碼的不同部分 因此,這里有三個迭代器,其中兩個的長度為100 ,第三個的迭代器直到100000 將矢量化想法放入簡潔的注釋文本中,並使用基於bsxfun的代碼解決您的問題-

%// Get vectorized equivalent of exp(-S.*X(j,2)) and keeping in mind that
%// since the last (3rd) dimension of final output has length same as the 
%// number of elements in X(:,2), so "throw" this to 3rd dim with permute. 
%// Then, use bsxfun to let the broadcasting being taken care off by MATLAB.
p1 = exp(-bsxfun(@times,V.',permute(X(:,2),[3 2 1]))); %//'

%// Going with same philosophy as before, get vectorized (Z.^X(j,1))
p2 = bsxfun(@power,V,permute(X(:,1),[3 2 1]));

%// Finally "merge" earlier two parts for final output
phi_out = bsxfun(@times,p1,p2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM