# How to apply looping in iteration process ?

5 views (last 30 days)
Andi on 17 Mar 2022
Commented: Mathieu NOE on 18 Mar 2022
Hi everyone,
I required to apply diffrent initail guess for iterative solutions. For a single solution, the following script works perfectly.
L = readmatrix('R_bounds_0.01.csv'); (coloumn matrix with 1986 rows)
for i=1:length(L);
f = @(n)((n+1)*log(n+1)-n)/n^2 - L(i);
n0 = 100; % Initial guess
n(i) = fzero(f,n0 );
disp(n );
end
nn=n';
csvwrite('N_lower_100.csv',nn);
However, i need to try with different values of initial guesses [0, 10, 100, 1000] etc. Someone suggets me a modified script but that is still not working,
m = length(A) ;
IG = [0, 10, 100, 1000] ; % initial guess
n = length(IG) ;
nn = zeros(m,n) ;
for i = 1:n
n0 = IG(i) ;
for j=1:m
f = @(n)((n+1)*log(n+1)-n)/n^2 - A(j);
nn(i,j) = fzero(f,n0 );
disp(nn(i,j) );
end
end
csvwrite('N_mean_10000.csv',nn);
May someone suggest me any possibel solution.
Thank you!
Andi on 18 Mar 2022
I agreed, sometime the initial guess is a bit far from the solution that why i used different initial guess. But that not works.

Walter Roberson on 17 Mar 2022
If your initial guess is not between about -1 and about +40 then you might not get a solution.
syms N
f = @(n)((n+1)*log(n+1)-n)/n^2;
baseeqn = f(N);
fplot(baseeqn, [-1.5 40])
hold on
minA = min(A)
minA = 0.0706
maxA = max(A)
maxA = 0.9681
yline([minA, maxA]);
ylim([minA-1/4, maxA+1/4])
hold off sol1 = vpasolve(baseeqn - A(1), 0.5)
sol1 =
15.859241089220361924912561179785
fplot(baseeqn, [32 40]); hold on;
yline([minA]);
hold off Mathieu NOE on 18 Mar 2022
hello
a very minor bug in the first code posted is the initialization of nn is done with the wrong dimensions (flip m and n)
I have no problel running the corected code - attached the output file
of course the IG must contains only values strictly above -1 (otherwise log(n+1) is complex) and different from zero (division by zero)
m = length(A) ;
IG = [0.0001,0.001, 0.01, 0.1, 1, 10, 100, 1000] ; % initial guess (n> - 1) and (n # 0)
n = length(IG) ;
nn = zeros(n,m) ; % mod here
for i = 1:n
n0 = IG(i) ;
for j=1:m
f = @(n)((n+1)*log(n+1)-n)/n^2 - A(j);
nn(i,j) = fzero(f,n0 );
disp(nn(i,j) );
end
end
csvwrite('N_mean_10000.csv',nn);

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!