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.

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 28 Okt. 2016

0 Stimmen

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

8 Kommentare

Sherwin
Sherwin am 28 Okt. 2016
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;
Sherwin
Sherwin am 28 Okt. 2016
Thanks a million!!
Sherwin
Sherwin am 28 Okt. 2016
Bearbeitet: Sherwin am 28 Okt. 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?

Jan
Jan am 28 Okt. 2016
@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.
Sherwin
Sherwin am 28 Okt. 2016
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
Walter Roberson
Walter Roberson am 29 Okt. 2016
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by