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

1 回表示 (過去 30 日間)
David Hughes
David Hughes 2015 年 8 月 3 日
コメント済み: Star Strider 2015 年 8 月 3 日
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))

採用された回答

Star Strider
Star Strider 2015 年 8 月 3 日
You would get that error when any value is entered.
Change this to start with 1 rather than zero:
k = 1;
  2 件のコメント
David Hughes
David Hughes 2015 年 8 月 3 日
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 2015 年 8 月 3 日
My pleasure.
I can almost guarantee you that most of us here have made that same error at one time or another.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by