我是matlab的新手,所以我不知道所有的快捷方式,matlab必须使代码更高效,更快.我一直在matlab中将一些东西拼凑在一起做家庭作业,同时专注于完成作业而不是效率.现在我发现我花了更多的
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而不是循环,使用冒号.例如:
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())