4

I am new to matlab so I do not know all the shortcuts matlab has to make the code more efficient and faster. I have been hacking together something in matlab for a homework assignment while focusing on completing the assignment rather than efficiency. Now I'm finding that I'm spending more time waiting on the program than actually coding it. Below is a headache of nested for loops that takes forever to finish. Is there a faster or efficient way of coding this 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
1
  • 9
    Please tell us the gist of what it's doing so we can make sense of what your code is doing. Seeing variables named "i, i2, i3" is never a good sign.... Commented Nov 1, 2011 at 21:38

1 Answer 1

8

Instead of looping, use colons. For example:

                    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

Can be written as:

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

After you find all places where this can be done, learn to use indexing instead of looping, e.g.,

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 line may not work if mappedGX is a matrix, and i2/j2 don't represent a rectangular sub-matrix. In such a case you will need sub2ind())

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.