index exceeds array bounds error

12 visualizaciones (últimos 30 días)
Zack Rabas
Zack Rabas el 7 de Nov. de 2018
Comentada: Zack Rabas el 7 de Nov. de 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?

Respuesta aceptada

TADA
TADA el 7 de Nov. de 2018
Editada: TADA el 7 de Nov. de 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 comentario
Zack Rabas
Zack Rabas el 7 de Nov. de 2018
Thank you, the vectorized way is much easier

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Startup and Shutdown en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by