在MATLAB中避免循环缓慢

时间:2018-02-08 10:10:55

标签: matlab for-loop

我试图在MATLAB中避免缓慢的for循环。我有RGB图像,我正在尝试手动计算马哈拉诺比斯距离。以下是关于mahalanobis距离函数的示例代码,它适用于for循环:

H = 10;
W = 20;
im = rand(H,W,3);
Mean = rand(1,3);
SigmaInv = rand(3,3);   
[size1, size2, size3] = size(im);
imDistance = zeros(size1,size2);
for i = 1:size1
    for j = 1:size2
        x(:,:) = (im(i,j,:));
        x1 = transpose(x);
        imDistance(i,j) = sqrt((x1-Mean)*SigmaInv*transpose(x1-Mean));
    end
end

im维度是[HxWx3],平均维度是[1x3],SignaInv [3x3]和输出imDistance应该是[HxW]。我认为如果我使用bsxfun和permute函数代码会更快,但我无法弄清楚如何实现它。感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

使用reshape function

非常简单
H = 10;
W = 20;
im = rand(H,W,3);
Mean = rand(1,3);
SigmaInv = rand(3,3);   
[size1, size2, size3] = size(im);

sm = SigmaInv * transpose(Mean);

im_flat = reshape(im,size1*size2,3);
calc = sqrt((im_flat - Mean) * sm);
imDistance = reshape(calc,size1,size2);