2016-11-01 24 views
0

我希望矢量化這個for循環。這個循環是關於獲取圖像像素的座標並按行排列形成一個數組。有沒有一種方法在MATLAB中矢量化這個循環?

rows = 812; % 812x650 image 
cols = 650; 
n=rows*cols; % total number of pixels 

index = zeros(n,2); % n coordinates of image pixels 
pt_homo = zeros(3,1,n); % [x,y,1]' 

k=1; 
for r=1:rows 
    for c=1:cols 
     index(k,1)=c; 
     index(k,2)=r; 
     pt_homo(1,1,k) = c; 
     pt_homo(2,1,k) = r; 
     pt_homo(3,1,k) = 1; 
     k=k+1; 
    end 
end 
+0

什麼是'n','rows','cols'。 [如何創建一個最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) – mpaskov

+0

我的不好,我編輯了這個問題 – CathIAS

回答

5

所以,如果我明白你的問題正確這應該解決它

c = 1:cols; 
r = 1:rows; 
[X Y] = meshgrid(r,c); 
index = [Y(:) X(:)]; 
pt_homo_ = permute([index ones(size(index,1),1)],[2 3 1]); 

基本上我所做的是創建索引的載體和使用meshgrid創建索引的矩陣,然後重新排序是在你想要的格式。

相關問題