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.

 Accepted Answer

r2 = 2:4;
[m, n] = ind2sub([4 16],r2)
(n-1)*60

8 Comments

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!!
Sherwin
Sherwin on 28 Oct 2016
Edited: Sherwin on 28 Oct 2016

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

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!