% basic_intro.m   2011-11-14
% basic examples
clear; clc;
disp(sprintf(' MATLAB example: basic_intro.m'));
%
separator = '=========================================================================';
N=4;
disp(sprintf('%s\n%s', separator, 'FOR Loop example:'));
for i=1:N
    disp (sprintf('i = %d',i));
end

disp(sprintf('%s\n %s', separator, 'IF statement example:'));
EPSILON = 1.0e-07;
%
x = -0.0000001;
if ( x > 0.0) 
    disp(sprintf('%s', 'x is positive'));
elseif ( abs(x) <= EPSILON) 
    disp(sprintf('%s', 'x is zero'));
else
    disp(sprintf('%s', 'x is negative'));
end

disp(sprintf('%s\n %s', separator, 'WHILE Loop example:'));

COUNT_LIMIT = 10;    % maximum count for the while loop
CONV_CRIT = 1.0e-05;  % convergence criterion

diff = 1.0e+06;   % initialise the difference to a large number
T_old = 4.0;      % initial guess for T
knt = 0;          % initialise the loop counter
CONV_FLAG =0;     % set the flag for convergence to false

while ( (knt < COUNT_LIMIT) & (CONV_FLAG == 0) )
%
   knt = knt +1;  % increment the loop counter
%
   % update T value using Newton-Raphson method
   T_new = T_old - ((T_old)^3 -27.0)/(3.0*(T_old)^2);
%
   diff = T_new - T_old;
%
   disp(sprintf('%s %d %s %12.7f %s %12.7f %s %13.6e\n ', 'iter', knt,  ...
    'T_old =',T_old, 'T_new=',T_new, 'diff=',diff));

% check convergence
   if ( abs(diff) <= CONV_CRIT )   % note absolute value of the difference
      CONV_FLAG = 1;
      disp(sprintf('%s %d %s', 'Root search CONVERGED in ',knt, 'iterations'));
   end
%
   T_old = T_new;
end  %end of while loop

if (CONV_FLAG == 0)
    disp(sprintf('%s %d %s', 'Root search did not converge in ',COUNT_LIMIT, 'iterations'));
end

disp(sprintf('%s\n', separator));