iteration using for loop is not working
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Image Analyst
on 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
b
c
10 Comments
Walter Roberson
on 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
b
c
digits(10)
vpa(a)
vpa(b)
vpa(c)
Walter Roberson
on 6 Mar 2022
Edited: Walter Roberson
on 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.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!