MATLAB: Creating an image of first non-zero values in a 3d matrix

3d matrixfindfirst non zerosMATLAB

Hi everyone,
I have a 2300x2475x109 datacube/ 3d matrix (109 images with 2300×2475 pixels). All images are binary (0 and 1). Now I want to create an image where each pixel contains the index of the first non-zero value. So for example, if the pixel 500×1500 is always zero until to the 12th image, the value in the result image should be 12. I could write a code, where this works for a single pixel location:
pixval = im_datacube(500,1500,:);
pixval = squeeze(pixval);
firstNonZero = find(pixval~=0, 1, 'first');
But now I want to make that for each pixel location and merge it all together into a single image. I tried to do it with loops, but i failed so far. Hope you can help me, thanks in advance.

Best Answer

[maxval,firstNonZero] = max(im_datacube ~= 0, [], 3);
firstNonZero(~maxval) = NaN; % pixel where 1 is not found along the 3rd dim
firstNonZero