I can't understand the syntax of Part, namely what does , do. The documentation says that

expr[[i,j,...]] or Part[expr,i,j,...]
is equivalent to expr[[i]][[j]]... 

however when I do

m = RandomInteger[9, {3, 4}];
m[[All, 2]] == m[[All]][[2]]

I get False.

  • 3
    $\begingroup$ All is special in this case, because m[[All]] is just m, and so m[[All,2]] being the second column of the matrix is not equal to m[[All]][[2]], which is the second row. $\endgroup$ – march Oct 22 '15 at 18:42
  • 3
    $\begingroup$ Don't be too quick to trust the documentation when it says something is equivalent to something else. More often than not, it's not true. Here the intent is just to say that values separated by commas apply to the successive levels of the expressions, so it's unfortunate that the documentation references a false equivalence that just causes confusion. Maybe it should say "generically equivalent"--i.e., without taking into account special values, or performance characteristics. $\endgroup$ – Oleksandr R. Oct 22 '15 at 18:43
  • 4
    $\begingroup$ m == m[[All]], m[[1, 2]] == m[[1]][[2]]. $\endgroup$ – Karsten 7. Oct 22 '15 at 18:44
  • 1
    $\begingroup$ Note that m[[All]] == m is True and so m[[All]][[2]] == m[[2]] is also True $\endgroup$ – Enrique Pérez Herrero Oct 22 '15 at 18:44
  • 1
    $\begingroup$ The documentation also shows another situation in which these are not equivalent. $\endgroup$ – Karsten 7. Oct 22 '15 at 18:49

Your misunderstanding of how Part works has nothing to do with comma, which is simply a delimiter (arguably the only delimiter Mathematica has). The documentation is correct when it says "expr[[i, j, ... ]] or Part[expr, i, j, ...] is equivalent to expr[[i]][[j]]... " providing the indices i, j, .. all represent integers. In Part, the position of the indices in Part determine the level at which the index should be applied. For example, m[[2, 3]] extracts 2nd element at level 1 of m and then extracts the 3rd element from that (which was at level 2 in m). Thus,

m = {{a, b, c}, {c, d, e}};
m[[2, 3]] == m[[2]][[3]] == e

All is a special token that, when it appears in Part, tells Mathematica to effectively map Part at that level. That is,

m[[All, 3]]

{c, e}

is effectively the same as

Part[#, 3] & /@ m


m[[All, {1, 3}]]

{{a, c}, {c, e}}

is effectively the same as

Part[#, {1, 3}] & /@ m

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.