【问题标题】:Is there a way to vectorize this loop in MATLAB?有没有办法在 MATLAB 中对这个循环进行矢量化?
【发布时间】:2016-11-01 20:59:31
【问题描述】:

我希望将这个 for 循环向量化。这个循环是关于获取图像像素的坐标并按行顺序形成一个数组。

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

【问题讨论】:

标签: matlab vectorization


【解决方案1】:

所以如果我正确理解你的问题,这应该可以解决它

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 创建索引矩阵,然后将其重新排序为您想要的格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多