Problem understanding this "for" loop

조회 수: 2 (최근 30일)
Tilemachos Marmaras
Tilemachos Marmaras 2022년 11월 29일
댓글: Tilemachos Marmaras 2022년 11월 29일
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

답변 (1개)

Jan
Jan 2022년 11월 29일
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
Tilemachos Marmaras
Tilemachos Marmaras 2022년 11월 29일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Direct Search에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by