Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I vectorise this range find over columns in a matrix in MATLAB?

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
like image 294
A.R.Ferguson Avatar asked Dec 05 '25 14:12

A.R.Ferguson


1 Answers

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).

like image 62
Luis Mendo Avatar answered Dec 07 '25 15:12

Luis Mendo