Part not behaving the way I expect it to

p = {{1, 0, 0}, {0, 1, 0}, {0, 1, 0}};
p[[All, 3]][[1 ;; 2]] = {1, 1};
p


I want to replace the first two elements of the third column of a 3x3 identity matrix.

The above code does not work. I get a depth-error message.

Set::partd: Part specification is longer than depth of object

I am confused because the following code is functional.

p[[All, 3]][[1 ;; 2]]

• try p[[1 ;; 2, 3]] = {1, 1}?
– kglr
Jun 15, 2017 at 1:18
• @kglr, thank you so much!!
– 吴剑涛
Jun 15, 2017 at 1:32

The way Set works in setting parts of an expression is this:

symb[[..<part specification>..]] = values;


The component symb must be a symbol (i.e. with head Symbol).

In the OP's code,

p[[All,3]][[1;;2]] = {1,1};


The symb component is p[[All,3]], which is not a symbol.

Fix as @kglr suggests,

p[[1 ;; 2, 3]] = {1, 1};


As for evaluating p[[All,3]][[1;;2]], you can see the procedure in Trace[p[[All, 3]][[1 ;; 2]]]. First p[[All, 3]] is evaluated. The expression then becomes

{0, 0, 0}[[1 ;; 2]]


(If p is meant to be the identity matrix, then the third row is wrong.)

• Yeah, got, thank you!!!:)
– 吴剑涛
Jun 15, 2017 at 1:35
• @吴剑涛 You're welcome. :) Jun 15, 2017 at 1:36
• @吴剑涛 If this fully answers your question in a satisfactory way it is appropriate for you to Accept it. Jul 5, 2017 at 2:34