Problem understanding this "for" loop

2 views (last 30 days)
Hello, I have this part of a code that I struggle understanding because of the "for" loop syntax, specifically inside the "if" statement. I don't require you to understand the mathematics, but only explaining to me what exactly is happening.
% Initialize constants
ALPHA = 0.1;
BETA = 0.5;
MAXITER = 100;
% Initialize variables
[m, n] = size(A);
xx = zeros(n,MAXITER);
% Define function, gradient and Hessian
f = @(x) sum(x.*log(x));
df = @(x) log(x)+1;
ddf = @(x) diag(1./(x));
% Main loop
x = x0;
for outer = 1:MAXITER
% Find search direction
g = -df(x);
H = [ddf(x) A' ; A zeros(m)];
dxv = H\[g; zeros(m,1)];
dx = dxv(1:n);
xx(:,outer) = x;
% Check terminating condition
l2 = g'*dx;
if (l2/2 <= tol)
xx = xx(:,1:outer);
x = xx(:,outer);
return;
end

Answers (1)

Jan
Jan on 29 Nov 2022
Before the loop xx is pre-allocated to the maximum number of iterations.
The for loop runs from 1 until MAXITER. The variable outer is the loop counter.
The criterion for convergence is the condition of the if command. It it is reached, the output xx is cropped until the current value of outer. Then the function is left.
Mostlikely you have omitted the function definition in the first line.
function [x, xx] = YourNewton()
A trailing end is missing also.
  1 Comment
Tilemachos Marmaras
Tilemachos Marmaras on 29 Nov 2022
Thank you! Yes, the function definition is in the first line indeed. There is an end below as well, as I said it was only a part of the code.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!