[英]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.
我试图用arrayfun找出一种方法,但还没有打到任何东西。
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). 它利用了
max
的第二个输出给出第一个最大化器(对于每个列)的位置这一事实。
我不确定这是否更快,但num2cell
+ cellfun
似乎是对列上的常规函数进行矢量化的唯一方法:
r = cellfun(@(x)range(find(x)),num2cell(img,1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.