How can I update initial value of an array in a for loop?

a(1)=0.1, a(2)= 0.11;
for k=2:10^10
a(k+1)= a(k)+a(k-1)+.....
if a(k+1)> 5.0
Up = k ;
end
end.
It takes a lot of memory as iteration number is very high.
How can I update the initial value like a(3)=a(2); a(1)=a(2)
and find new a(3) till my condition is satisfied.

6 commentaires

Do a little research on preallocation.
What is the purpose of
count = count + 1;
I removed count. I need to save the value of k when the condition is satisfied.
I have a(1) and a(2) from which I will calculate a(3). After that change a(2) to a(1) and a(3) to a(2) until my condition a(3) > my threshold is satisfied. I just need to know what value of k or iteration my condition is satisfied
Greg
Greg le 10 Fév 2018
Modifié(e) : Greg le 10 Fév 2018
I'm assuming the initial conditions (first two values), or the threshold change? Otherwise, this is a trivial problem and k never changes.
My comment on preallocation comes from the ambiguity of a(k+1)= a(k)+a(k-1)+..... This made me think you needed the entire vector.

Connectez-vous pour commenter.

 Réponse acceptée

Greg
Greg le 10 Fév 2018
Modifié(e) : Greg le 10 Fév 2018
Use 3 separate variables, with a slight fix to the value assignment you suggested in the question. Also, throw a break inside the condition - or better, use a while loop (with the counter).
one = 0.1;
two = 0.11;
for k=2:10^10
three = one + two;
if three > 5.0
break
end
two = three;
one = two;
end

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements 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!

Translated by