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

3 Answers 3

14
$\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$
3
  • $\begingroup$ Yeah, got, thank you!!!:) $\endgroup$
    – 吴剑涛
    Commented Jun 15, 2017 at 1:35
  • $\begingroup$ @吴剑涛 You're welcome. :) $\endgroup$
    – Michael E2
    Commented Jun 15, 2017 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
    Commented Jul 5, 2017 at 2:34
3
$\begingroup$
p = {{1, 0, 0}, {0, 1, 0}, {0, 1, 0}};

f = MapAt[1 &, {1 ;; 2, 3}];

f @ p

{{1, 0, 1}, {0, 1, 1}, {0, 1, 0}}

If we want to change p inline we can use ApplyTo (new in 12.2)

p //= f;

p

{{1, 0, 1}, {0, 1, 1}, {0, 1, 0}}

$\endgroup$
1
$\begingroup$

Using SubsetMap:

p = {{1, 0, 0}, {0, 1, 0}, {0, 1, 0}};

SubsetMap[{1, 1} &, p, {{1, 3}, {2, 3}}]

(*{{1, 0, 1}, {0, 1, 1}, {0, 1, 0}}*)
$\endgroup$

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.