1
votes

I have a binary segmentation of a solid object in a Matlab 3D array called mask (1000x1000x1000 uint16). I need to extract the top surface, i.e., the first non-zero element for each column vector (over the second and third dimensions). I can do this with the following code snippet:

s = zeros(1000,1000); 
for y=1:1000
    for x=1:1000
        s(x,y) = find(mask(:,x,y),1);
    end 
end

Is there a way to vectorize the code and avoid the for loops?

1

1 Answers

2
votes

Find the indices of the maximum value (one in your case). Squeeze these indices to remove singleton dimensions and convert into the desired form (s).

[~, ind] = max(mask); 
s = squeeze(ind);