You could use the faster FEX: Shuffle instead of RANDPERM. But unfortunately this function is not threadsafe currently and the replied random numbers will be equal in each thread. Allocating buyWeights repeatedly consumes time. Better set it to zero:
buyWeights = zeros(rows-1,cols);
parfor i=1:numSimuls
buyWeights(:) = 0;
...
But here the PARFOR is a problem also. I cannot test this currently, but I guess this could help for both problems:
block = round(linspace(1, numSimuls + 1, numberOfCores + 1));
parfor iCore = 1:numberOfCores
buyWeights = zeros(rows-1,cols);
Shuffle(rand(1,4) * 2^32, 'seed');
for iS = block(iCore):block(iCore + 1) - 1
buyWeights(:) = 0;
buySignal = Shuffle(rows-1, 'index', numHoldingPeriods);
buyRandomAssetPicks = Shuffle(cols, 'index', numStocks);
buyWeights(buySignal,buyRandomAssetPicks) = 1/numStocks;
profit(iS) = sum(stockReturns(:) .* buyWeights(:));
end
end
In addition it is avoided to calculate the sum over the 2nd dimension at first, because this means accessing elementes spread through wide sections of the RAM. Better create the sum over the first dimension at first:
b = sum(stockReturns .* buyWeights, 1);
profit(iS) = sum(b);
Or join it to one SUM command as in the example above.
NOTE: Please test and debug this, because it is written from the scratch in a text editor.
Best Answer