MATLAB代码的矢量化

时间:2014-03-23 21:10:45

标签: matlab vectorization

我试图将以下MATLAB代码矢量化以提高性能:

for IX = 2:NSCX
    for IY = 2:NSCY
        for IC = 1:Nc

                duplicate = 0;
                for IK = 1:IA(IX-1,IY-1,1)
                    if IA(IX-1,IY-1,IK+1) == IC
                        duplicate = 1;
                    end
                end
                if duplicate == 0
                    IA(IX-1,IY-1,1) = IA(IX-1,IY-1,1)+1;
                    IA(IX-1,IY-1,IA(IX-1,IY-1,1)+1) = IC;
                end
            end
        end
    end
end
IA是三维矩阵(大小(IA)= NSCX NSCY 9)。有人能帮忙吗。感谢。

1 个答案:

答案 0 :(得分:0)

你应该考虑另一种方式去这里。你应该看一下函数histc,它找到第一个值,其中样本比之前的样本大,小于下一个样本。对于您,可以为每个维度完成此操作。这将为每个未排序的单元格提供和索引。我不知道适用于+8居住细胞的条件是什么,但我想在排序后可以应用这些条件。

1维histc的示例

a = [1 5 7 12];
b = 2:2:16;
[c,d] = histc(a,b)

d给出b的索引,其中每个a属于,c是所有非空索引的逻辑。

编辑:用于创建具有histc

的常规网格网格的伪代码
cellX = vector with all regular x centers (or borders?!)
cellY = vector with all regular y centers (or borders)
px = all unstructured x centers
py = all unstructured y centers
[~,xind] = histc(px,cellx); % which cellX does px belong too?
[~,yind] = histc(py,celly); % which cellY does py belong too?
% Code for properly taking care of indices to match wanted format
unstructuredPerStructured = accumarray(indVector, properInd,...) % find number of unstructured cells per structured.

由于您的代码不可运行且不符合堆栈交换所需的输入/输出标准,我仍然不确定您的输出,但这似乎是一个很好的方法。

编辑:histc()的应用

我试图按照您的建议做一些事情,但我无法复制以前代码的结果。我发布了运行代码link所需的变量。

NSCX = 20;
NSCY = 20;

cellX = reshape(Xsdc,numel(Xsdc),1);% vector with all regular x centers (or borders?!)
cellY = reshape(Ysdc,numel(Xsdc),1);% vector with all regular y centers (or borders)
px = eince(:,1);% all unstructured x centers
py = eince(:,2);% all unstructured y centers

[y1,i1] = sort(cellX);
[y2,i2] = sort(cellY);

[~,xind] = histc(px,y1); % which cellX does px belong too?
[~,yind] = histc(py,y2); % which cellY does py belong too?

xindrevert = i1(xind);
yindrevert = i2(yind);

for i = 1:Nc
    [a,b] = find(cellX == cellX(xindrevert(i)));
    [c,d] = find(cellY == cellY(yindrevert(i)));
    index = c.*NaN;
    for j = 1:length(c)
        check = a(a == c(j))';
        if ~isempty (check)
            index(j) = check;
        end
    end
    output(i) = index(~isnan(index));
end
unstructuredPerStructured = accumarray(output',1,[NSCX*NSCY,1]); % find number of unstructured cells per structured
unstructuredPerStructured = reshape(unstructuredPerStructured,NSCX,NSCY);

unstructuredPerStructured应该等于IA(:,:,1),但不是。你能看到这个问题吗?我猜测差异是由于服用细胞中心。