9
$\begingroup$
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]]
$\endgroup$
  • 3
    $\begingroup$ try p[[1 ;; 2, 3]] = {1, 1}? $\endgroup$ – kglr Jun 15 '17 at 1:18
  • $\begingroup$ @kglr, thank you so much!! $\endgroup$ – 吴剑涛 Jun 15 '17 at 1:32
12
$\begingroup$

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.)

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

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.