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.
0 件のコメント
回答 (1 件)
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!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!