index exceeds array bounds error

12 Ansichten (letzte 30 Tage)
Zack Rabas
Zack Rabas am 7 Nov. 2018
Kommentiert: Zack Rabas am 7 Nov. 2018
I have a list of numbers in an array and I need to sum them up based on a condition. The program needs to add numbers in particular position if and only if that number is greater than the previous number. The first number in the array is excluded For example, if the array is 4,5,3,7,9,6 the program will sum 5 + 7 + 9. Here is what I am trying to run, but it is not working.
list = input('Enter a list of positive intergers separated by commas:', 's');
value = strsplit(list, ','); value = str2double(value);
uppLim = length(value);
while value
for i = 1:uppLim
y = value(i);
x = value(i+1);
if y < x
result = x;
elseif y > x
result = 0;
templateStr = 'The sum of the numbers = %0.0f';
toDisplay = fprintf(templateStr, result);
disp(toDisplay);
end
end
end
my error being returned is "index exceeds array bounds". What is going wrong?

Akzeptierte Antwort

TADA
TADA am 7 Nov. 2018
Bearbeitet: TADA am 7 Nov. 2018
uppLim = length(value) - 1;
Should solve your problem. Oh and drop the
while value
which is basically an endless loop because value doesn't change inside the loop. it's also not necessary because the
for i = 1:uppLim
doesn't enter the loop when value is empty.
I would also ditch the for loop, and vectorize it
list = input('Enter a list of positive intergers separated by commas:', 's');
value = strsplit(list, ','); value = str2double(value);
x = sum(value([false diff(value) > 0]));
disp(['The sum of the numbers = : ' num2str(x)]);
  1 Kommentar
Zack Rabas
Zack Rabas am 7 Nov. 2018
Thank you, the vectorized way is much easier

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by