请更高效的Matlab代码

时间:2011-11-01 21:34:25

标签: performance matlab

我是matlab的新手,所以我不知道所有的快捷方式,matlab必须使代码更高效,更快。我一直在matlab中将一些东西拼凑在一起做家庭作业,同时专注于完成作业而不是效率。现在我发现我花了更多的时间等待程序,而不是实际编码。下面是嵌套for循环的头痛,需要永远完成。如果没有那么多的forloops,是否有更快或更有效的编码方式?

for i = 1:ysize
for j = 1:xsize
    MArr = zeros(windowSize^2, 2, 2);
    for i2 = i - floor(windowSize/2): i + floor(windowSize/2)
        if i2 > 0 && i2 < ysize + 1
            for j2 = j - floor(windowSize/2): j + floor(windowSize/2)
                if j2 > 0 && j2 < xsize + 1
                    mat =  weight*[mappedGX(i2,j2)^2, mappedGX(i2,j2)*mappedGY(i2,j2); mappedGX(i2,j2)*mappedGY(i2,j2), mappedGY(i2,j2)^2];
                    for i3 = 1:2
                        for j3 = 1:2
                            MArr(windowSize*(j2-(j - floor(windowSize/2))+1) + (i2-(i - floor(windowSize/2)) + 1),i3,j3) = mat(i3,j3);
                        end
                    end
                end
            end
        end
    end
    Msum = zeros(2,2);
    for k = size(MArr)
        for i2 = 1:2
            for j2 = 1:2
                Msum = Msum + MArr(k,i2,j2);
            end
        end
    end
    R(i,j) = det(Msum) - alpha*(trace(Msum)^2);
    R = -1 * R;
end
end

1 个答案:

答案 0 :(得分:8)

使用冒号而不是循环。例如:

                    for i3 = 1:2
                        for j3 = 1:2
                            MArr(windowSize*(j2-(j - floor(windowSize/2))+1) + (i2-(i - floor(windowSize/2)) + 1),i3,j3) = mat(i3,j3);
                        end
                    end

可以写成:

 MArr(windowSize*(j2-(j-floor(windowSize/2))+1)+(i2-(i-floor(windowSize/2))+1),:,:)=mat;

找到可以完成此操作的所有地方后,学习使用索引而不是循环,例如,

i2 = i - floor(windowSize/2): i + floor(windowSize/2);
i2=i2(i2>0 && i2<ysize+1);
j2 = j - floor(windowSize/2): j + floor(windowSize/2);
j2=j2(j2>0 && j2<xsize+1);
mat =  weight*[mappedGX(i2,j2)^2, mappedGX(i2,j2)*mappedGY(i2,j2); 

(高级用户请注意:如果mappedGX是矩阵,则最后一行可能无效,i2 / j2不代表矩形子矩阵。如果您需要sub2ind()