MATLAB: Datacube indexing speed up

2d3ddatacubeindexingloopsMATLABspeedxyz

I use some weighted probability routines and the following code is to slow. Is there a way to optimize it? I already preallocated everything.
function normalizedFrame = normalizer (currentFrame, normalizedFrame, oneLevelFrame, dataCube, maxADU) %#codegen
%

for i = maxADU:-1:1
oneLevelFrame(currentFrame==i) = 1;
dataCube(:,:,i) = oneLevelFrame;
oneLevelFrame = zeros(31, 31);
currentFrame(currentFrame==i) = currentFrame(currentFrame==i)-1;
end
%
possitionsIn3dCube = find(dataCube);
[row, col, ~] = ind2sub(size(dataCube), possitionsIn3dCube);
index = randi(length(row));
photonPossition = [row(index), col(index)];
normalizedFrame(photonPossition(1), photonPossition(2)) = 1;
Best regards, Alex

Best Answer

A little more efficient would be
for i = maxADU:-1:1
idx == currentFrame == i;
oneLevelFrame(idx) = 1;
dataCube(:,:,i) = oneLevelFrame;
oneLevelFrame = zeros(31, 31);
currentFrame(idx) = currentFrame(idx)-1;
end
Could you confirm that there is no further code in the routine than what you show here? In particular, that there is no further code that uses currentFrame? Because if that is true, there is a more efficient version that does not use loops.