필터 지우기
필터 지우기

While Loop Question (Ungraded)

조회 수: 2 (최근 30일)
Brian Peoples
Brian Peoples 2019년 2월 13일
댓글: Steven Lord 2020년 9월 14일
F = [1,1]
evensum = zeros(1,4000000);
while F < 4000000
if F == 1
evensum(1,F) = F;
else
evensum = evensum(1,F-1) + evensum(1,F-2);
end
F = F+1
end
The question is:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 1, the first 10 terms will be: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
• Your task is to consider the terms in the Fibonacci sequence whose values do not exceed four million, and find the sum of the even-valued terms.
• Use a while loop.
• Create a vector F, whose first two elements are 1 and 1, and each additional element is calculated in the while loop using the Fibonacci sequence.
• Again use the rem function to determine if a number is even.
Name your variable for the sum of the even-valued terms evensum
I am unable to avieve this. Does anybody know where I went wrong and can help? This is an ungraded question.

답변 (2개)

Yasasvi Harish Kumar
Yasasvi Harish Kumar 2019년 2월 13일
You have started with F as an array but use it in the while loop and if condition as a variable.
The solution to your problem can be achieved by assigning the array F with indicies.
The following code should be able to solve your problem.
F = [1,1];
evensum = 0;
i = 2;
while F(i) < 4000000
i = i+1;
F(i) = F(i-1) + F(i-2);
if rem(F(i),2) ==0
evensum = evensum + F(i);
end
end

Faizalbhai Vahora
Faizalbhai Vahora 2020년 9월 13일
Write a MATLAB function evensum(n) that calculates:
s = 2^2-4^2+6^2-8^2+.......+(-1)^(n+1)*(2*n)^2
how can i sol this problem in matlab
  댓글 수: 1
Steven Lord
Steven Lord 2020년 9월 14일
This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance. But since this isn't really related to the original question of this discussion, you should post your code as a new question.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.

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

카테고리

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