More efficient matlab code, please

I am new to Matlab, so I don’t know, all Matlab shortcuts should make the code more efficient and faster. I hacked into something in Matlab for a homework assignment, focusing on completing the assignment rather than efficiency. Now I have found that I spend more time on the program than actually coding it. Below is a headache for nested loops that end forever. Is there a faster or more efficient way to code without so many 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 
+4
source share
1 answer

Use colons instead of loops. For instance:

  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 

It can be written as:

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

Once you find all the places where this can be done, learn to use indexing instead of a loop, for example,

 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); 

(Note for advanced users: the last row may not work if mappedGX is a matrix, and i2 / j2 do not represent a rectangular submatrix. In this case, you need sub2ind() )

+8
source

Source: https://habr.com/ru/post/1379223/


All Articles