Iterating over an Array Using a “for” Loop.

조회 수: 576 (최근 30일)
Donald Hersam
Donald Hersam 2016년 4월 17일
이동: DGM 2023년 2월 6일
This is a very basic question and I would appreciate any help. I've written code to calculate the Fibonacci sequence using a for loop. I want to display the elements of the sequence whose indices are specified in the array “N”. The problem is that all displayed values are the same as the value associated with the first element of “N”.
N=[10 100 1000];
first=1;
second=1;
for i=1:(N-2) %The index has to have two terms removed because it starts with 1 and 1 already
next=first+second; %The current term in the series is a summation of the previous two terms
first=second; %Each term must by iterated upwards by an index of one
second=next; %The term that previously was second is now referred to as next
end
for i=1:length(N)
disp([N(i) next])
end
Thanks
  댓글 수: 2
Donald Hersam
Donald Hersam 2016년 4월 17일
이동: DGM 2023년 2월 6일
Thanks for the quick response, but what this loop seems to do is tell me the entirety of the series. I was only looking for a response that returns the value at the 10, 100 and 1000th place mark on the series.
Maryam Omar Maabreh
Maryam Omar Maabreh 2023년 2월 5일
이동: DGM 2023년 2월 6일
for i=start : step : last+1
% ...
end
Where step is the increment to i.
In your case, your looking for
for i=1 : 10 : 10001
i = i*10;
% ...
end

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2016년 4월 17일
편집: Image Analyst 2016년 4월 17일
Donald, regarding your new "Answer", you can do it like this:
N=[10 100 1000];
for n = 1 : length(N)
first=1;
second=1;
for k = 3 : N(n) %The index has to have two terms removed because it starts with 1 and 1 already
next = first+second; %The current term in the series is a summation of the previous two terms
first = second; %Each term must by iterated upwards by an index of one
second = next; %The term that previously was second is now referred to as next
end
% Print to command window
next
end

추가 답변 (1개)

MathWorks Support Team
MathWorks Support Team 2020년 9월 2일
이동: DGM 2023년 2월 6일
Use a “for” loop to calculate the elements of the Fibonacci sequence for the maximum value in “N”. Then, use another “for” loop to display the values by indexing into the calculated sequence.
N = [10 100 1000];
f(1) = 1;
f(2) = 1;
for i = 3:max(N)
f(i) = f(i-1) + f(i-2);
end
for i = 1:numel(N)
disp(f(N(i)))
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by