Keep getting the error "Index exceeds the number of array elements (1)"

조회 수: 1 (최근 30일)
Alexis Williams
Alexis Williams 2021년 3월 29일
답변: Arjun 2024년 9월 6일
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.

답변 (1개)

Arjun
Arjun 2024년 9월 6일
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!

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by