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 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Alan Clemenson
am 8 Apr. 2018
Kommentiert: Alan Clemenson
am 8 Apr. 2018
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 Kommentare
David Fletcher
am 8 Apr. 2018
Bearbeitet: David Fletcher
am 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.
Akzeptierte Antwort
David Fletcher
am 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);
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!