Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient Matlab Code please

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
like image 952
jyim89 Avatar asked Feb 23 '23 13:02

jyim89


1 Answers

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

like image 163
cyborg Avatar answered Mar 02 '23 19:03

cyborg