簡體   English   中英

如何在MATLAB中的矩陣中找到列的列?

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

基本上我有一個圖像蒙版,我想在每列中找到圖像的寬度。 有沒有辦法將其矢量化以提高速度? 我試圖用arrayfun找出一種方法,但還沒有打到任何東西。

r = zeros(1,cols);
for i = 1 : cols
    r(i) = range(find(img(:,i)));
end

以下代碼以矢量化方式與您的代碼相同:

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;

它利用了max的第二個輸出給出第一個最大化器(對於每個列)的位置這一事實。

我不確定這是否更快,但num2cell + cellfun似乎是對列上的常規函數​​進行矢量化的唯一方法:

r = cellfun(@(x)range(find(x)),num2cell(img,1));

find + unique方法 -

[row1,col1]  = find(img);
[~,start1] = unique(col1,'first');
[~,stop1] = unique(col1);
r = row1(stop1) - row1(start1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM