index exceeds array bounds error

12 次查看(过去 30 天)
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?

采纳的回答

TADA
TADA 2018-11-7
编辑:TADA 2018-11-7
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)]);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by