Ahmad Siavashi
Ahmad Siavashi

Reputation: 999

Evaluation of loop condition takes too long

In the following script,

syms x1 x2 x3;
f = -x1-x2-x3;
u = 1;
B = -log(20 - x1) - log(20 - x2) - log(25 - x3) - log(log(x1) - x2) - log(30 - x1 - x2) - log(30 - x1 - x3) - log(x1) - log(x2) - log(x3);
Theta = f + u * B;
% LS (x0, a, b, c)
xk = [5; 1.5; 5];
e = 0.1;
% Back Tracking (b, c, a)
b = 0.5;
c = 0.1;
a = 1;
% Hoising
D_Theta = gradient(Theta);
% LS Algorithm
while (norm(subs(D_Theta, [x1; x2; x3], xk)) >= e)
    Pk = - subs(D_Theta, [x1; x2; x3], xk);
    % Back Tracking Algorithm
    while (double(subs(Theta, [x1; x2; x3], xk + a * Pk)) > double(subs(Theta, [x1; x2; x3], xk) + c * a * Pk' * subs(D_Theta, [x1; x2; x3], xk)))
       a = a * b;
       double(a)
    end
    xk = xk + a * Pk;
    double(xk)
end

the time to evaluate the condition of the inner loop (line 19) is surprisingly so long (i.e. it takes hours!).
What is the reason and how can it be fixed?

Upvotes: 0

Views: 38

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

Unless you have any specific need of keeping your numeric variables symbolic, just make them numeric:

change your the lines to xk=double(xk); and the iterations wont increase in time consumption, as the biggest problem of your code is that the number in xk gets more and more terms in each iteration.

With this change, the whole code takes 9.7s in my PC

Upvotes: 1

Related Questions