Why do I get subscript indices error?
显示 更早的评论
Hi, I have a code like this,
r2 = randi([2 64]);
[m, n] = ind2sub([4 16],r2);
n = (n-1)*60;
CH1(m:end,n:end) = P2(m:end,n:end);
CH1 and P2 are two matrices. I generated 'r2' randomly and used 'ind2sub' to find the indices of the element r2. So I expected m and n to be numbers, but I get this error:
??? Subscript indices must either be real positive integers or
logicals.
Please help.
采纳的回答
r2 = 2:4;
[m, n] = ind2sub([4 16],r2)
(n-1)*60
8 个评论
Sorry, I don't get it. Would you please explain it a little?
You have
CH1(m:end,n:end) = P2(m:end,n:end);
so you are using n as a subscript.
You used
n = (n-1)*60;
That will come at as 0 if n was 1 before executing that statement.
When can n come out as one in reaching that statement? If
[m, n] = ind2sub([4 16],r2)
is to have the second output come out as 1 then the value being converted, r2, must have been in the first column of the 4 x 16 matrix. That would be the case of r2 was one of 1, 2, 3, or 4. Is that possible? Let us look to see where r2 came from:
r2 = randi([2 64]);
Well that cannot be 1, but it can be 2, 3, or 4. Let us double check that by setting the values to 2, 3, or 4 specifically and trying:
r2 = 2:4;
[m, n] = ind2sub([4 16],r2)
(n-1)*60
and indeed the 3 outputs of (n-1)*60 are 0, and 0 is not a valid subscript.
The bug is either in your bounds for randi, or in your manipulation n = (n-1)*60
Perhaps you wanted
n = (n-1) * 60 + 1;
Thanks a million!!
In the rest of the code I used a similar method,
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
This time 'r' and 'c' can't be zero, but I get the same error here! Would you please help me with this too?
@Sherwin: The spam flag has been set by accident, most likely. Or perhaps "thanks a million" is too near to "win a million" ;-) I've removed the flag.
Thank you so much :)
You should use the debugger
dbstop if error
and run. When it stops, tell us what the values of r and c and r3(i) are
You asked this later question at http://www.mathworks.com/matlabcentral/answers/309643-why-do-i-get-an-index-error and it was answered there.
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
标签
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!选择网站
选择网站以获取翻译的可用内容,以及查看当地活动和优惠。根据您的位置,我们建议您选择:。
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 MathWorks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- América Latina (Español)
- Canada (English)
- United States (English)
欧洲
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
