Rightmost Digit Counter Script - Index exceeds array bounds

20 visualizaciones (últimos 30 días)
Obadah M.
Obadah M. el 13 de Nov. de 2018
Comentada: Guillaume el 13 de Nov. de 2018
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)

Respuestas (1)

Guillaume
Guillaume el 13 de Nov. de 2018
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 comentarios
Obadah M.
Obadah M. el 13 de Nov. de 2018
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 el 13 de Nov. de 2018
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

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