Home > front end >  Nested For loops in MATLAB - Possibility for optimization?
Nested For loops in MATLAB - Possibility for optimization?

Time:08-30

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?

CodePudding user response:

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)
  • Related