Essentially I have an image mask and I want to find the width of the image in each column. Is there a way to vectorise this for speed? I tried to figure out a way with arrayfun but haven't hit on anything yet.
r = zeros(1,cols);
for i = 1 : cols
r(i) = range(find(img(:,i)));
end
The following code does the same as yours in a vectorized manner:
imglog = img~=0; %// convert to 0 and 1 values
[~, i1] = max(imglog); %// i1 is the position of the first 1
[~, i2] = max(flipud(imglog)); %// size(img,1)+1-i2 is the position of the last 1
r = size(img,1)+1-i2 - i1;
It exploits the fact that the second output of max gives the position of the first maximizer (for each column).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With