Vectorize Evaluations of Meshgrid Points

1 Ansicht (letzte 30 Tage)
_Ben_
_Ben_ am 24 Aug. 2015
Beantwortet: Varun Bhaskar am 26 Aug. 2015
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

Antworten (1)

Varun Bhaskar
Varun Bhaskar am 26 Aug. 2015
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:

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by