iteration using for loop is not working

2 vues (au cours des 30 derniers jours)
shiv gaur
shiv gaur le 6 Mar 2022
a(1)=0;
b(1)=1;
c(1)=0;
n=1;
for n=1:5
a(2)=0.5*(a(1)-b(1));
b(2)=0.5*((a(1))-(b(1))-(a(1)*c(1)));
c(2)=0.5*((a(1)*b(1)-c(1)));
a(1)=a(2);
b(1)=b(2);
c(1)=c(2);
n=n+1;
end
disp(a(2))
how to run this program to give from old value to new value using iteration a(2) giving more than five value

Réponses (1)

Image Analyst
Image Analyst le 6 Mar 2022
Try it like this:
numElements = 5;
a = zeros(1, numElements);
b = ones(1, numElements);
c = zeros(1, numElements);
for n = 2 : numElements
a(n) = 0.5*(a(n-1)-b(n-1));
b(n) = 0.5*((a(n-1))-(b(n-1))-(a(n-1)*c(n-1)));
c(n) = 0.5*((a(n-1)*b(n-1)-c(n-1)));
end
a
a = 1×5
0 -0.5000 0 0 0
b
b = 1×5
1.0000 -0.5000 0 0 0
c
c = 1×5
0 0 0.1250 -0.0625 0.0312
  10 commentaires
Walter Roberson
Walter Roberson le 6 Mar 2022
numElements = 20;
a = sym(zeros(1, numElements));
b = sym(ones(1, numElements));
c = sym(zeros(1, numElements));
for n = 2 : numElements
a(n) = (1/sym(n))*10*(a(n-1)-b(n-1));
b(n) = (1/sym(n))*((28*a(n-1))-(b(n-1))-(a(n-1)*c(n-1)));
c(n) = (1/sym(n))*((a(n-1)*b(n-1)-3.3*c(n-1)));
end
a
a = 
b
b = 
c
c = 
digits(10)
vpa(a)
ans = 
vpa(b)
ans = 
vpa(c)
ans = 
Walter Roberson
Walter Roberson le 6 Mar 2022
Modifié(e) : Walter Roberson le 6 Mar 2022
numElements = 10;
syms a [1 numElements]
syms b [1 numElements]
syms c [1 numElements]
for n = 2 : numElements
a(n) = (1/sym(n))*10*(a(n-1)-b(n-1));
b(n) = (1/sym(n))*((28*a(n-1))-(b(n-1))-(a(n-1)*c(n-1)));
c(n) = (1/sym(n))*((a(n-1)*b(n-1)-3.3*c(n-1)));
end
Ea = expand(a);
Ca = vpa(findSymType(Ea, 'number'),5);
[~, idx] = sort(abs(Ca), 'desc');
format long g
double(reshape(Ca(idx(1:10)),[],1))
ans = 10×1
1.0e+00 * 2.14539347488294e+24 2.1388215038686e+24 -1.97683468274523e+24 -1.66919049501844e+24 1.57009953308725e+24 -1.53553980415839e+24 1.25698231464319e+24 -1.12800014100977e+24 -1.03005272271465e+24 1.02716449593526e+24
So by the time you get to 10, you are working with coefficients as large as 2*10^24
Ca0 = vpa(findSymType(expand(subs(Ea, [sym('a1'), sym('a3')], [0,0])),'number'),5);
[~, idx] = sort(abs(Ca0), 'desc');
double(reshape(Ca0(1:10), [], 1))
ans = 10×1
1.0e+00 * -9.35288582447091e+18 -6.04096409393064e+18 -1.99711770767288e+18 -1.57887744010591e+18 -1.23085737821287e+18 -3.24385496525373e+17 -2.04394672654123e+17 -5.32546405724897e+16 -4.96159656693842e+16 -4.67790559622922e+16
And after you take into account that a and c start out as 0, you are still working with coefficients in the 10^18 range by the time you get to numElements = 10.
It isn't MATLAB messing up: your formulas are not working out for b as large as 1. If b were less than 1, then you might get very different results.

Connectez-vous pour commenter.

Tags

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by