Vectorize Evaluations of Meshgrid Points
1 回表示 (過去 30 日間)
古いコメントを表示
Hello,
I need the "for" loop in the following representative section of code to run as efficiently as possible. The mean function in the code is acting as a representative placeholder for my own function.
x = linspace(-1,1,15);
y = linspace(2,4,15);
[xgrid, ygrid] = meshgrid(x,y);
mc = rand(100000,1);
z=zeros(size(xgrid));
for i=1:length(xgrid)
for j=1:length(ygrid)
z(i,j) = mean(xgrid(i,j) + ygrid(i,j) + xgrid(i,j)*ygrid(i,j)*mc);
end
end
I have vectorized the code and improved its speed by about 2.5 times by building a matrix in which mc is replicated for each grid point. My implementation results in a very large matrix (3 x 2250000) filled with repeated data. I've mitigated the memory penalty of this approach by converting the matrix to single precision, but it seems like there should be a more efficient way to do what I want that avoids replicating so much data. I found the post below which is similar to my problem, but the accepted answer is essentially what I am already doing. Help vectorizing 2 For loops with meshgrid and subscripts
0 件のコメント
回答 (1 件)
Varun Bhaskar
2015 年 8 月 26 日
Hi,
You can parallelize your code to improve efficiency. Since this is a Monte Carlo simulation, where each run is independent of another, you can use the parfor construct instead of the outermost for loop. Refer to the following useful links in order to make your code run on different cores:
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Detection についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!