index exceeds array bounds error
13 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
TADA
on 7 Nov 2018
Edited: TADA
on 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)]);
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!