0
$\begingroup$

I have a 2D array (array) of length 10x10

array = ImageData[RandomImage[10, 10]];

and I have a list of indices for the desired array elements.

desired = {{1, 3}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, 
  {3, 3}, {3, 4}, {3, 5}, {3, 6}, {4, 3}, {4, 4}, {4, 5}, {4, 6}, {5, 
  2}, {5, 3}, {5, 4}, {5, 5}, {5, 6}, {6, 2}, {6, 3}, {6, 4}, {6, 
  5}, {6, 6}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {8, 3}, {8, 4}, {8, 
  5}, {8, 6}};

One way to access the desired elements is array[[desired[[i,1]],desired[[i,2]]]].

But I think there must be some better approaches to do this. Therefore, my question is: how smartly can this be done?

$\endgroup$
  • $\begingroup$ desired[[i]] ? $\endgroup$ – Ulrich Neumann Jan 31 '18 at 9:54
2
$\begingroup$

Extract

Extract[Array[x, {10, 10}], desired]

{x[1, 3], x[1, 4], x[1, 5], x[1, 6], x[2, 3], x[2, 4], x[2, 5], x[2, 6], x[3, 3], x[3, 4], x[3, 5], x[3, 6], x[4, 3], x[4, 4], x[4, 5], x[4, 6], x[5, 2], x[5, 3], x[5, 4], x[5, 5], x[5, 6], x[6, 2], x[6, 3], x[6, 4], x[6, 5], x[6, 6], x[7, 3], x[7, 4], x[7, 5], x[7, 6], x[8, 3], x[8, 4], x[8, 5], x[8, 6]}

Extract[array, desired] 

{7.26511, 0.161259, 3.68567, 3.39165, 7.61135, 4.81733, 3.86941, 9.2501, 0.627509, 6.31271, 9.98706, 4.64997, 5.17223, 4.92969, 5.886, 5.401, 5.62913, 3.50379, 6.28734, 6.12715, 7.69792, 7.2367, 3.36751, 8.13952, 2.09141, 1.7609, 9.10072, 1.05672, 1.78437, 3.22518, 1.44075, 3.28318, 7.89254, 6.47532}

Part + Apply

array[[##]] & @@@ desired  == %

True

Table

Table[array[[## & @@ i]], {i, desired}] == %

True

$\endgroup$
  • 1
    $\begingroup$ Extract[array,desired] looks to be the simplest and most compact one. $\endgroup$ – Majis Jan 31 '18 at 10:05
  • 1
    $\begingroup$ and fastest as well. $\endgroup$ – Majis Jan 31 '18 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.