How do I bypass Error (index must be a positive integer or logical)?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
David Hughes
am 3 Aug. 2015
Kommentiert: Star Strider
am 3 Aug. 2015
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 Kommentare
Akzeptierte Antwort
Star Strider
am 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 Kommentare
Star Strider
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!