My while loop is giving an error "Array indices must be positive integers or logical values." I'm trying to calculate the golden ratio within epsilon 0.001.

1 view (last 30 days)
I am stuck in the initiation of my while loop. I attached the file and an image of the code. I've done everything I can think of but I'm still learning and can't see what I'm doing wrong here.
  2 Comments
David Fletcher
David Fletcher on 8 Apr 2018
Edited: David Fletcher on 8 Apr 2018
There are a couple of issues that I can immediately see:
You've set k=0 and are indexing x(k), x(k-1), and x(k-2) in your while loop. In Matlab, array indices start at 1 so all of these indexing operations are invalid. You've also set N=3:k - since k=0 this equates to 3:0 which is an empty array since your end value is less than your start value and you haven't set a negative step value.
Alan Clemenson
Alan Clemenson on 8 Apr 2018
Thank you, I thought I could make k count until false and that final k value would fill that space in N. Is there a way I can do that?

Sign in to comment.

Accepted Answer

David Fletcher
David Fletcher on 8 Apr 2018
Probably something more like this:
%Program Description:
%This program takes 2 numerical inputs and calculates/estimates the golden
%ratio within epsilon 0.001.
%
% Record of Revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 4/7/18 Alan Clemenson Original Code
%
%User Prompts
n1=input('type in value for first #: ');
n2=input('type in value for second #: ');
% Compute results
%index for the numbers following n1&n2 in the fibonacci sequence 'x'.
%Previous fib no.
x(1) = n2-n1
% Place Assignment of n1&n2 in the sequence
x(2)= n1
x(3)= n2
%the absolute value of the difference between two ratios>0.001
while (abs(x(3)/x(2)-x(2)/x(1))>0.001);
%The Fibonacci sequence.
nextFib=x(2)+x(3);
x=circshift(x,-1);
x(3)=nextFib;
Ratio=x(3)/x(2);
end
fprintf('\n The Golden Ratio = %f \n',Ratio);

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!