Given a matrix M=RandomReal[{0},{5,5,5}]; How can I identify elements with a list?


In[81]:= M[[5,5,5]]

Out[81]= 0.

M[[#]]&/@{{5,5,5}} Doesn't work, no matter how much Flatten[]

There has to be an easier way than

In[83]:= a={2,2,2}
Out[83]= {2,2,2}
In[87]:= M[[a[[1]],a[[2]],a[[3]]]]
Out[87]= 0.

Apologies, I know there is probably a extremely simple answer... Thanks for anyone who takes a look.

Edit* I would also like to adjust the identified element which has given a number of errors. M[[{5,5,5}]]=1 Using @J.M. s solution

In[7]:= M2[[##]] & @@ allcells[[-1]] = +1

During evaluation of In[7]:= Set::write: Tag Apply in (M2[[##1]]&)@@{5,5,5} is Protected.

Out[7]= 1
  • 2
    $\begingroup$ Try M[[##]] & @@ {5,5,5}. $\endgroup$ Mar 23, 2018 at 1:35
  • $\begingroup$ @J.M. Awh! Awesome! Thanks a lot just for complete I'm using M[[##]] & @@@ {{5,5,5},{4,4,4},{5,4,5}} but I doff my dunce cap' $\endgroup$
    – Teabelly
    Mar 23, 2018 at 1:38
  • $\begingroup$ If you figured out how it works, I invite you to write an answer to your own question. ;) $\endgroup$ Mar 23, 2018 at 1:45
  • $\begingroup$ You might also want have a look at Extract. For example, Extract[M, {{5, 5, 5}}] returns {0.}. This might seem to be artificial, but Extract also works with lists of lists, e.g. idx = RandomInteger[{1, 5}, {10, 3}]; Extract[M, idx]. In this case, you may also use M[[##]] & @@@ idx, but this unpacks arrays and is thus several magnitudes slower than Extract. $\endgroup$ Mar 23, 2018 at 9:30
  • $\begingroup$ @J.M. @HenrikSchumacher How can I edit the element? I seem to be getting an error In[7]:= M[[##]] & @@ a[[-1]] = +1 During evaluation of In[7]:= Set::write: Tag Apply in (M[[##1]]&)@@{5,5,5} is Protected. Out[7]= 1 $\endgroup$
    – Teabelly
    Mar 23, 2018 at 11:35

1 Answer 1


The fundamental difference here, though subtle yet important, is between M[[a,b,c]] and M[[{a,b,c}]], the key part being (pun not intended) the curly brackets around a,b,c.

The first one gives what you want, and it's even in the form of your "expected" code, whereas the second one deals with a different functionality of Part, or rather the [[...]] code.

The M[[{a,b,c}]] code gives a list of elements of M at positions a,b,c, rather than the single element at the multidimensional position {a,b,c}.

Relating to your example, and as you already showed, the code M[[5,5,5]] gives the single element 0. at position {5,5,5}, whereas the code M[[{5,5,5}]] gives the list of elements each at position 5 in the first level of M.

  • $\begingroup$ I actually laughed at 'the key Part being'... now I feel bad. $\endgroup$
    – Teabelly
    Mar 24, 2018 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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