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.

2 次查看(过去 30 天)
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 个评论
David Fletcher
David Fletcher 2018-4-8
编辑:David Fletcher 2018-4-8
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 2018-4-8
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?

请先登录,再进行评论。

采纳的回答

David Fletcher
David Fletcher 2018-4-8
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);

更多回答(0 个)

类别

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