How do I bypass Error (index must be a positive integer or logical)?
1 回表示 (過去 30 日間)
古いコメントを表示
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))
0 件のコメント
採用された回答
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 件のコメント
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 Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!