How can I update initial value of an array in a for loop?
조회 수: 5 (최근 30일)
이전 댓글 표시
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
Greg
2018년 2월 10일
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.
채택된 답변
Greg
2018년 2월 10일
편집: Greg
2018년 2월 10일
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
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!