Rightmost Digit Counter Script - Index exceeds array bounds

조회 수: 3 (최근 30일)
Obadah M.
Obadah M. 2018년 11월 13일
댓글: Guillaume 2018년 11월 13일
As the title suggests, this code is supposed to count how many numbers end with a certain digit in a vector.
For instance, I want to count how many numbers end with the digit 7.
So, [342, 657, 1, 578, 1886, 1757] is supposed to return 2 since there are only two numbers that end with digit 7.
However, I get this error: Index exceeds array bounds.
Error in inclassExercise (line 13)
if rightDigit(numbers(k)) == 7
I'm just a beginner so bare with me.
clear, clc
numbers = input('Enter the numbers as a vector: \n');
numbersString = num2str(numbers); % convert number to string
digitNumber = numel(numbersString); % calculate how many digits in a number
rightDigit = str2double(numbersString(digitNumber)); % get the rightmost digit
count = 0;
for k = 1:length(numbers)
if rightDigit(numbers(k)) == 7
count = count + 1;
end
end
fprintf('The number of integers whose rightmost digit is 7 is: %d\n', count)

답변 (1개)

Guillaume
Guillaume 2018년 11월 13일
The best way for you to understand the problems with your code (unfortunately there are many), is to debug it yourself. Step through your code one line at a time in the debugger and see what actually happens to each variable compared to what you expected. Pay particular attention to the size of the variables as well. I don't even understand why you expect rightDigit to have more than one element when you explicitly state in a comment that it is the (one) rightmost digit.
Note that while you can indeed solve your assignment by converting to character and extracting the last character of each number, that's not particularly efficient. A simpler method would be think about the remainder of the division of each number by 10.
  댓글 수: 2
Obadah M.
Obadah M. 2018년 11월 13일
Thank you for your input.
I managed to get it working using the rem() function like you suggested.
clear, clc
numbers = input('Enter the numbers as a vector: \n');
count = 0;
for k = 1:length(numbers)
if rem(numbers(k), 10) == 7
count = count + 1;
end
end
fprintf('The number of integers whose rightmost digit is 7 is: %d\n', count)
Guillaume
Guillaume 2018년 11월 13일
Yes, as you see it is much simpler. It's even possible to get the count without a loop, in just one line.
I would still recommend that you test your original code through the debugger, so that you can understand what you did wrong. Making mistakes and understanding them is actually a very good way to learn the right way to do things.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by