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?
0 件のコメント
採用された回答
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 Center および File Exchange で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!