While Loop Question (Ungraded)

1 vue (au cours des 30 derniers jours)
Brian Peoples
Brian Peoples le 13 Fév 2019
Commenté : Steven Lord le 14 Sep 2020
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.

Réponses (2)

Yasasvi Harish Kumar
Yasasvi Harish Kumar le 13 Fév 2019
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 le 13 Sep 2020
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 commentaire
Steven Lord
Steven Lord le 14 Sep 2020
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by