what is the function of (sub2ind)

5 visualizzazioni (ultimi 30 giorni)
Alaaeldin Mohamed
Alaaeldin Mohamed il 3 Feb 2018
Modificato: per isakson il 8 Feb 2018
a = eval(['sub2ind(20.*ones(1,20)'',20,1' ');'])
  1 Commento
John D'Errico
John D'Errico il 3 Feb 2018
Modificato: John D'Errico il 3 Feb 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;

Accedi per commentare.

Risposta accettata

Jan
Jan il 4 Feb 2018
Modificato: Jan il 5 Feb 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.

Più risposte (0)

Categorie

Scopri di più su File Operations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by