# ind2sub doesn't work

4 visualizaciones (últimos 30 días)
Egor el 18 de Jul. de 2014
Comentada: Egor el 18 de Jul. de 2014
Check it out:
>> A = zeros(3);
>> A(2,3) = 1
A =
0 0 0
0 0 1
0 0 0
>> tmp = A'
tmp =
0 0 0
0 0 0
0 1 0
>> [maxVal, maxInd] = max(tmp(:))
maxVal =
1
maxInd =
6
And now the WTF comes:
>> ind2sub(size(tmp), maxInd)
ans =
6
>> ind2sub(maxInd, size(tmp))
ans =
3 3
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Alfonso Nieto-Castanon el 18 de Jul. de 2014
Editada: Alfonso Nieto-Castanon el 18 de Jul. de 2014
You are funny.
ind2sub reshapes the siz first argument to match the number of output variables used (in your case a single output argument), so that the resulting subscripts suffice to fully index the original elements. In your case:
ind2sub(size(tmp), maxInd)
is just the same as:
ind2sub(numel(tmp), maxInd)
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Egor el 18 de Jul. de 2014
thanks! I am really funny :)

Iniciar sesión para comentar.

### Más respuestas (2)

Matt J el 18 de Jul. de 2014
>> [i,j]=ind2sub(size(tmp), maxInd)
i =
3
j =
2
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Egor el 18 de Jul. de 2014
thanks!

Iniciar sesión para comentar.

James Tursa el 18 de Jul. de 2014
Editada: James Tursa el 18 de Jul. de 2014
The typical use of ind2sub in your case is to request two outputs:
[I J] = ind2sub(size(tmp), maxInd)
I =
3
J =
2
Which is the correct row & column for the index passed to the function.
What you have done is this:
ind2sub(size(tmp), maxInd) --> ind2sub([3 3], 6)
So you have asked a function that is typically expecting to produce two outputs (the number of elements in the first argument) to instead produce only one output. It did the only reasonable thing given the way you called it (less than the expected number of outputs) ... it returned the single linear index into your single output variable.
ind2sub(maxInd, size(tmp)) --> ind2sub(6,[3 3])
So you have told the function the dimension of the matrix is 1x6 and you have two indexes you want to convert to subscripts ... a 3 and a 3. So it did the correct conversion. Three elements into a 1x6 matrix yields the subscript 3. That's again a correct result.
You should probably re-read the doc on ind2sub, particularly the section on "Effects of Returning Fewer Outputs".
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Egor el 18 de Jul. de 2014
thank you! I read through 'help' function, so expected it always to return 2D value.

Iniciar sesión para comentar.

### Categorías

Más información sobre MATLAB en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by