iteration using for loop is not working
Afficher commentaires plus anciens
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)
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
b
c
10 commentaires
shiv gaur
le 6 Mar 2022
shiv gaur
le 6 Mar 2022
Torsten
le 6 Mar 2022
It is working, but the recursion gives high values for a, b and c for numElements being a large number.
shiv gaur
le 6 Mar 2022
Torsten
le 6 Mar 2022
Then your recursion is wrong.
shiv gaur
le 6 Mar 2022
Image Analyst
le 6 Mar 2022
We did not evaluate the "correctness" of your formula. I simply used it as is. If your formula is wrong, then correct it. I really have no idea what the "next" value might be based on the prior values, so all I can do is to assume you wrote down the formulas correctly. If you didn't, only you know what the correct formulas should be, not us.
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
b
c
digits(10)
vpa(a)
vpa(b)
vpa(c)
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))
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))
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.
Catégories
En savoir plus sur Operations on Strings 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!


