필터 지우기
필터 지우기

Vectorize Evaluations of Meshgrid Points

조회 수: 2 (최근 30일)
_Ben_
_Ben_ 2015년 8월 24일
답변: Varun Bhaskar 2015년 8월 26일
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

답변 (1개)

Varun Bhaskar
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:

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by