How to store each iteration value and plot it ?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi everyone I would like to store each L2 values after each iteration and plot it vs iteration number. How can I do it with the attached code?
clc;
clear all;
n=input('Enter the no of iterations : \n');
N=n+1;
a=input('\n Enter lower limit : \n');
b=input('\n\nEnter upper limit : \n');
fold=1;
fnew=1;
func = @(x)(.65-[.75/(1+x^2)]-.65*x*atan(1/x));
for i=1:N
if i==1 || i==2
f(i)=1;
continue;
end
f(i)=fold+fnew;
fold=fnew;
fnew=f(i);
end
L2=(b-a)*f(N-2)/f(N);
j=2;
while j<N
L1=(b-a);
if L2>L1/2
anew=b-L2;
bnew=a+L2;
else
if L2<=L1/2
anew=a+L2;
bnew=b-L2;
end
end
k1=func(anew);
k2=func(bnew);
if k2>k1
b=bnew;
L2=f(N-j)*L1/f(N-j+2);
else
if k2<k1
a=anew;
L2=f(N-j)*L1/f(N-(j-2));
else
if k2==k1
b=bnew;
L2=f(N-j)*[b-a]/f(N-(j-2));
j=j+1;
end
end
end
j=j+1;
end
disp(a);
disp(b);
Réponse acceptée
dpb
le 31 Août 2018
Preallocate for L2 and keep and increment an index inside the loop and store into an array
L2=zeros(N,1); % preallocate
L2(1)=(b-a)*f(N-2)/f(N); % save initial value
j=2;
while j<N
L1=(b-a);
if L2>L1/2
...
every store is then
L2(j)=...;
Or, change to counted for loop instead of while since there's no conditional exit.
L2(1)=...;
for j=2:N-1
...
L2(j)=...;
...
BTW, Matlab "elseif" is one string, I had to reformat code to try to read it for indention levels being all fouled up where you wrote
...
else if L2<=L1/2
...
Rewrite
if L2>L1/2
anew=b-L2;
bnew=a+L2;
else
if L2<=L1/2
anew=a+L2;
bnew=b-L2;
end
end
as
if L2>L1/2
anew=b-L2;
bnew=a+L2;
elseif L2<=L1/2
anew=a+L2;
bnew=b-L2;
end
which since the 'elseif' is the negation of the 'if' condition, this is really
if L2>L1/2
anew=b-L2;
bnew=a+L2;
else
anew=a+L2;
bnew=b-L2;
end
there's no need for the conditional if on the else clause here.
4 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!