For loop producing correct values but returning zeros
Show older comments
Working on what should be a very simple task. A for loop that follows the equation
for n number of times, and stores each result in the array Z. As each iteration runs, the correct number is generated then stored, however, beyond roughly iteration 8 or so, it resets the previous numbers to zero and sets the rest to infinity (or zero) depending on how I write it. I'm not sure what I'm doing wrong?
% n = 100;
% c=0.25
% z = zeros(1,n);
% z(1,1) = 1;
% z(1,2) = 1
% for i = 1:(n-1)
% z(1, i+1) = ((z(1,i))^2 + c);
% end
% plot(z)
n = 100;
c=0.25
z = zeros(1,n);
z(1,1) = 1;
z(1,2) = 1
for i = 1:(n-1)
z(1, i+1) = ((z(1,i))^2 + c);
end
plot(z)
Accepted Answer
More Answers (1)
"it resets the previous numbers to zero"
That's not correct. The first few iterations' results appear to be zero on the plot because they are so small compared to later iterations' results (but you can change the y scale to logarithmic to see them better). They also appear to be zero on the command line for the same reason (but you can change the format of command-line format to see them better).
"sets the rest to infinity"
That is correct: at some point the numbers become larger than the largest representable double-precision floating-point number, so they are stored as Inf.
n = 100;
c=0.25;
z = zeros(1,n);
z(1,1) = 1;
z(1,2) = 1;
for i = 1:(n-1)
z(1, i+1) = ((z(1,i))^2 + c);
end
semilogy(z) % plot on log scale
% the first few elements of z appear to be zero:
z
% but they're not really:
z(1:6)
z(7)
z(8)
z(9)
z(10)
z(11)
z(12)
z(13)
z(14)
% adjusting the command-line format:
format longG
z(:)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

