Why do I get an index error?
51 次查看(过去 30 天)
显示 更早的评论
Here in this part of my code
r3 = randi([1 N],[G 1]);
for i = 1:G
ch = ceil(r3(i,1)/3840);
[r, c] = ind2sub([4 960],r3-((ch-1)*3840));
if Ma{ch,1}(r,c) == 0
Ma{ch,1}(r,c) = 1;
else
Ma{ch,1}(r,c) = 0;
end
end
'r' and 'c' can't be zero, but I get:
??? Subscript indices must either be real positive integers or
logicals
Would you please help me with this?
2 个评论
KSSV
2016-10-28
[r, c] = ind2sub([4 960],r3-((ch-1)*3840));
The values inside ind2sub should be positive integers. In your case they might be taking zeros and/or negative values. Check that.
回答(3 个)
Steven Lord
2016-10-28
On which line does this error occur?
If it's on the line where you define r3, you've probably created a variable named randi that is shadowing the built-in randi function.
For the line where you define ch, you've probably shadowed ceil.
In either of these cases, rename or remove the variable.
Guillaume
2016-10-28
It's not clear what you're trying to do with your code, but clearly it's not going to work
r3 is a vector with values between 1 and an unknown N. So, let's assume that r3(1) is N and r3(2) is 1. Because of the way you create ch it is an integer at least 1, and more if N > 3840. For the error you see, N must be at least 3841, so let's assume that,
So, for i = 1, r3(i) = 3840, and ch = ceil(3841/3840) = 2. You then have
r3 - ((ch-1)*3840) = [3841 1] - (1 * 3840) = [3841 1] - 3840 = [1 -3839]
As you can see you've got a very negative index here. It gets even worse if N > 2*3840.
Note that there is no point in the ind2sub call in your code. You could just as well use the linear index to index Ma{ch} with absolutely no change of behaviour.
3 个评论
Guillaume
2016-10-28
编辑:Guillaume
2016-10-28
I thought my demonstration was clear. Create the following variables:
N = 3841; %minimum value for the error to occur
r3 = [N; 1]; %a possible output of your randi. Don't need any more elements to break your code. G is irrelevant.
i = 1; %first pass of the loop
Now, look at the values of
ch = ceil(r3(i) / 3840) %is ceil(3841/3840) = 2
r3 - ((ch - 1) * 3840
You'll see that the output of the last expression is
[1; -3839]
Anyway, it would be much better if you told us what you're trying to achieve as I'm fairly certain you're going at it completely wrong.
David Goodmanson
2016-10-28
编辑:David Goodmanson
2016-10-28
Hi Sherwin, May be there shouldn't be negative indices, but there actually are negative indices, as Guillaume has pointed out. Here is an example, running your code:
G = 2;
r3 = [1; 3841];
for i = 1:G
ch = ceil(r3(i,1)/3840);
[r, c] = ind2sub([4 960],r3-((ch-1)*3840))
end
which for i=2 comes up with
c = -959
1
Perhaps you want to have r3(i,1) on the fourth line of your original code so as to make a single index instead of a vector's worth.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!