Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested For loops in MATLAB – Possibility for optimization?

Given n by n orthogonal matrix Q and diagonal matrix D such that all diagonal elements of D are nonnegative, I want to compute diagonal matrix T such that diagonal elements were equal to t(i)=1/(q(i,1)*q(i,1)*d(1)+q(i,2)*q(i,2)*d(2)+...+q(i,n)*q(i,n)*d(n)).

I am using Matlab:

Q=[0.7477 0.0742 0.6599; -0.5632 0.5973 0.5710; -0.3518 -0.7986 0.4883];
D=diag([0 0.7106 2.2967]);
n=length(Q);
L=Q*sqrt(D);
t = zeros(n,1);
for i=1:n
    for j=1:n
        t(i) = t(i) + sum(L(i,j)^2);
    end
end
T = sqrt(inv(diag(t)));

As you can see I have used nested for loops. Is it possible to avoid using loops at all?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for i=1:n
    for j=1:n
        t(i) = t(i) + sum(L(i,j)^2);
    end
end

What are you trying to do? sum sums more than one number, but L(i,j)^2 is one number.

Instead, we can use your code to sum over j indices and remove the loop.

for i=1:n
    t(i) = t(i) + sum(L(i,:).^2);
end

But, you defined t = zeros(n,1);, i.e. t has nothing in it, so your for loop is equivalent to:

for i=1:n
    t(i) = sum(L(i,:)^2);
end

Knowing this, we can do it in one go:

t = sum(L.^2,2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading