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

1 次查看(过去 30 天)
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