How to add the iteration code in MATLAB
Afficher commentaires plus anciens
I wanna ask how to add the iteration code, because now the code I do is keep using the old value of xr.
for iteration = 1:3
iteration = 0;
xl = 4
xu = 6
xr =(xl+xu)/2
Xr = xr
syms a b xl fxl
E2 = sym('fxl = a*xl + b')
fxl = solve(E2,'fxl')
fXl = subs(fxl,{xl,a,b},{4,2,3})
syms a b X_r fxr
E3=sym('fxr = a*X_r+ b')
fxr = solve(E3,'fxr')
fXr = subs(fxr,{X_r,a,b},{Xr,2,3})
PreviousApprox = Xr
Test = fXl * fXr
if Test < 0
Xu = xr
Xl = xl
Xr_new =(Xl +Xu)/2
CurrentApprox = Xr_new
error=(CurrentApprox-Xr)/CurrentApprox*100
elseif Test > 0
Xu = xu
Xl = Xr
Xr_new=(Xl +Xu)/2
CurrentApprox = Xr_new
error=(CurrentApprox-Xr)/CurrentApprox*100
else
Test = 0
CurrentApprox = Xr_new
error=(CurrentApprox-Xr)/CurrentApprox*100
disp('we got the root value');
break
end
ApproxErrorPercentage(iterations)=abs((CurrentApprox-PreviousApprox)/(CurrentApprox)*100)
end
1 commentaire
Alper Olca
le 27 Mar 2020
x1=5;
x2=5;
x3=5;
x4=5;
td=10^-2;
a=0;
for i= 1:10
a=0+i;
if( (abs(x1-x1)<td && abs(x2-x2)<td) && (abs(x3-x3)<td)&& abs(x4-x4)<td)
x1=(-23+x2-x3+2*x4)/4;
x2=(-21-2*x1+x3-3*x4)/6;
x3=(-11+x1+2*x2-x4)/5;
x4=(22+x1-2*x2+3*x3)/6;
end
k=(4*x1-x2+x3-2*x4);
l=(2*x1+6*x2-x3+3*x4);
m=(-x1-2*x2+5*x3+x4);
n=(-x1+2*x2-3*x3+6*x4);
end
rslt=[k l m n ; x1 x2 x3 x4]
Réponses (1)
Cam Salzberger
le 21 Mai 2018
Hello Mavis,
In each loop, it seems like you use a previous value of xr to create a new value of Xr_new. Generally, users making use of this design pattern will either update xr to the value of Xr_new at the beginning or end of the loop, or simply only ever use xr. For example:
Xr_new = 1;
for k = 1:10
xr = Xr_new;
seeHowGoodXrIs(xr)
Xr_new = updateValue(xr);
end
If you don't need to use the previous value more than once, it's generally easier to just do "in-place" updates to the value:
xr = 1;
for k = 1:10
seeHowGoodXrIs(xr)
xr = updateValue(xr);
end
Hope this helps!
-Cam
Catégories
En savoir plus sur MATLAB dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!