简体   繁体   English

制作3D数组MATLAB

[英]Making a 3d array MATLAB

In MATLAB I have 在MATLAB中

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

and I also have a 100000x2 matrix called X, each row has two sets of data - p is the first column and x is the 2nd. 我还有一个名为X的100000x2矩阵,每一行都有两组数据-p是第一列,x是第二列。

I want to compute exp^(-S*X(j,2)).(*Z.^X(j,1)) where j indexes the row. 我想计算j索引行的exp ^(-S * X(j,2))。(* Z. ^ X(j,1))。 The result should be a 100x100x100000 matrix. 结果应为100x100x100000矩阵。 This will then be averaged along the 3rd dimension and a mesh plot will be produced. 然后将沿第3维求平均值,并生成网格图。 I've tried using a for loop 我尝试过使用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

to produce the 100x100x100000 array I need. 产生我需要的100x100x100000阵列。 However this gives me the error 但这给我错误

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));

I'm not sure why this is happening? 我不确定为什么会这样吗? Can anyone figure out a better way of trying to find the result I want? 谁能找到一种更好的方法来尝试找到我想要的结果? Because I'm guessing there could be a fully vectorised solution (or least use of for loops)? 因为我猜测可能存在完全矢量化的解决方案(或至少使用for循环)?

Assume that you are using two more nested loops to get Z and S , thus the code would have three nested loops in total. 假设您要使用两个以上的嵌套循环来获取ZS ,因此该代码总共将具有三个嵌套循环。

Now, the vectorizing techniques haven't changed on vectorizable nested loops cases like these - Treat different parts of the code that involve different iterators separately . 现在,矢量化技术在像这样的可矢量化嵌套循环的情况下没有改变-分别处理涉及不同迭代器的代码的不同部分 Thus, here you have three iterators, two of which are 100 in length and the third ones goes until 100000 . 因此,这里有三个迭代器,其中两个的长度为100 ,第三个的迭代器直到100000 Putting the vectorizing ideas in a concise commented text and solving your case with bsxfun based code - 将矢量化想法放入简洁的注释文本中,并使用基于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