what is the function of (sub2ind)

5 views (last 30 days)
Alaaeldin Mohamed
Alaaeldin Mohamed on 3 Feb 2018
Edited: per isakson on 8 Feb 2018
a = eval(['sub2ind(20.*ones(1,20)'',20,1' ');'])
  1 Comment
John D'Errico
John D'Errico on 3 Feb 2018
Edited: John D'Errico on 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;

Sign in to comment.

Accepted Answer

Jan
Jan on 4 Feb 2018
Edited: Jan on 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.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!