Info

This question is closed. Reopen it to edit or answer.

Loops error index dimension?

1 view (last 30 days)
Maria De Silva
Maria De Silva on 17 Apr 2016
Closed: MATLAB Answer Bot on 20 Aug 2021
I'm trying to get my code to let me in put a range. Then in that range tell me how many prime numbers there are and what are they.
if true
% code
%Prompts user for range
initial=input('enter initial value of range');
final=input('enter final value of range');
for range=initial:final
prime_number(range)=primeter(range);
end
clc
%Number of prime number
number_prime_numbers=sum(prime_number);
Range=initial:final;
%Number on range which are prime
numbers_are_prime=Range(prime_number==1);
Numbers_are_prime=num2str(numbers_are_prime);
%Printing information to user
fprintf('There are %d prime numbers between %d and %d which are \n%s\n',number_prime_numbers,initial,final,Numbers_are_prime)
end
So this is my code. And it works when I give initial as 1 and final as 5 it gives me there are 3 prime number which are 2,3,5. But when I give a range of 10:20 it no longer works. It say index dimension error
  1 Comment
Maria De Silva
Maria De Silva on 17 Apr 2016
primeter is a function that I have made earlier.

Answers (1)

Geoff Hayes
Geoff Hayes on 17 Apr 2016
Maria - if I substitute my own function for your primeter, then I observe the same error message as you
Index exceeds matrix dimensions.
Error in *** (line ***)
numbers_are_prime=Range(prime_number==1);
This is because Range is initialized as
Range=initial:final;
and so is an array of 11 elements whereas prime_number is initialized as
for range=initial:final
prime_number(range)=primeter(range);
end
and so it is 20 elements since range starts at initial. And so the binary array returned from
prime_number==1
has 20 elements where the non-zero ones have an index of at least ten. Those with 12 or more are responsible for the error message.
I suspect that what you want to do instead is something like
for range=initial:final
prime_number(range-initial+1)=primeter(range);
end
so that prime_number is an array of final-initial+1 elements.
Try the above and see what happens!

This question is closed.

Tags

Community Treasure Hunt

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

Start Hunting!