Keep getting the error "Index exceeds the number of array elements (1)"
1 view (last 30 days)
Show older comments
Can someone please explain why I keep getting this error? Here is my code:
for Count = 1:100
fprintf('Count = %d\n', Count');
end
Wait = input('Press return to continue', 's');
x = 1;
while x <= 100 % test Count
disp(x)
x = x + 1; % modify Count
end
disp('Prime Numbers')
for num = 1:100
i = isprime(num);
primenum = num(i);
disp(primenum);
end
It is showing me that the error is located at the "primenum = num(i);" I am not sure why.
0 Comments
Answers (1)
Arjun
on 6 Sep 2024
I see that you are getting this error “Index exceeds number of array elements(1)”. It is also mentioned that the potential cause of the error is the line “primenum = num(i);”.
From the flow of your program, it can be interpreted that you want to display all the Prime Numbers between 1 to 100.
Let’s have a look at the problematic code snippet:
for num = 1:100
i = isprime(num);
primenum = num(i);
disp(primenum);
end
In the code above “num” is a variable which is supposed to be 1x1 dimensional variable i.e. a scalar and indexing scalars is not a good idea. The error creeps in due to this reason only that we are trying to index a scalar variable.
Instead, you can modify the snippet as follows to be error free:
for num = 1:100
if isprime(num)
disp(num);
end
end
This way we make sure that we don’t index any scalar variable and avoid any potential errors.
I hope it will help!
0 Comments
See Also
Categories
Find more on Matrix Indexing 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!