what is the function of (sub2ind)

5 visualizaciones (últimos 30 días)
Alaaeldin Mohamed
Alaaeldin Mohamed el 3 de Feb. de 2018
Editada: per isakson el 8 de Feb. de 2018
a = eval(['sub2ind(20.*ones(1,20)'',20,1' ');'])
  1 comentario
John D'Errico
John D'Errico el 3 de Feb. de 2018
Editada: John D'Errico el 3 de Feb. de 2018
More to the point, is why anyone in their right mind would ever want to write that code? A mess, with absolutely no good purpose.
Far better would be the simple:
a = 20;

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 4 de Feb. de 2018
Editada: Jan el 5 de Feb. de 2018
The line is extreme nonsense. As John has said already, all it does is assigning a=20 .
Without the confusing eval, it is:
a = sub2ind(20 .* ones(1,20)', 20, 1)
ones(1,20)' is the same as ones(20,1). If you multiply this by 20, you get a [20 x 1] column vector containing 20s. Using sub2ind interprets this vector as the size of an array (an extremely huge array with 20^20 elements, but it is not created explicitly). Now the "linear index" is determined for the element in the 20th row and 1st column. The linear index is useful to enumerate all elements of an array using one index. See e.g.:
a = rand(2, 3)
a(1:6)
The linear index is applied in columnwise order, and in the first row it equals the column index. As long as the first dimension has >= k elements, sub2ind(S, k, 1) replies k.
Hiding this hilarious code in an eval command seems to be a pure obfuscation: Useless code to impede the reading. Contact the author and buy him a cup of coffee.
  1 comentario
Alaaeldin Mohamed
Alaaeldin Mohamed el 4 de Feb. de 2018
Thank you for your excellent explaination

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre File Operations 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