How do I bypass Error (index must be a positive integer or logical)?

3 views (last 30 days)
I created a script that will give the average of the negative numbers entered by the user. I was attempting to store the entered values into a vector and then get the average of the elements. I get an error when a negative value is entered. How do I enter negative values for the vector?
%This script will ask the user for a negative number %The loop will end when a zero or positve number is entered. %Then the script will out put the average of the negative numbers clc clear x = input('Enter a negative number: '); i = 0; k = 0; xsum = 0; negvec = 0;
while x < 0 fprintf('You entered a %f.\n',x) negvec(1,k) = x; k = k + 1; i = i + 1; x = input('Enter another negative number: \n'); end
fprintf('Thank you, %d negative numbers entered.\n',i) fprintf('The average is %.2f \n\n',mean(negvec))

Accepted Answer

Star Strider
Star Strider on 3 Aug 2015
You would get that error when any value is entered.
Change this to start with 1 rather than zero:
k = 1;
  2 Comments
David Hughes
David Hughes on 3 Aug 2015
Thank you I totally missed that the vector would be start at position 0 with k = 0, and there is no position 0. Thanks.
Star Strider
Star Strider on 3 Aug 2015
My pleasure.
I can almost guarantee you that most of us here have made that same error at one time or another.

Sign in to comment.

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!