4
$\begingroup$

I try to simplify my encounter,so I post a question.But I aware that turn a unexpected direction.I try to re-assign the first and last element in a matix,such as I have:

mat={{1,2,3,4},{5,6,7,8},{9,10,11,12}}

How to get with a concise method?

{{a,2,3,4},{5,6,7,8},{9,10,11,b}}

And I try to use mat[[{{1,1},{-1,-1}}]]={a,b} to get what I want,I get some error information,despite I think I have not made syntax error.

$\endgroup$
  • 4
    $\begingroup$ list[[1, 1]] = a; list[[-1, -1]] = b keep it simple :) $\endgroup$ – Nasser Dec 27 '16 at 4:49
  • 1
    $\begingroup$ (list[[Sequence @@ First@#]] = Last@#) & /@ {{{1, 1}, a}, {{-1, -1}, b}}; list $\endgroup$ – Edmund Dec 27 '16 at 4:50
  • $\begingroup$ @Nasser Thanks. :) $\endgroup$ – yode Dec 27 '16 at 4:51
  • $\begingroup$ @Edmund Thanks,too :) $\endgroup$ – yode Dec 27 '16 at 4:53
  • 1
    $\begingroup$ mat[[{{1,1},{-1,-1}}]] is in fact a syntax error. It does not correspond to any case listed in the documentation. If you remove the outer braces, you get a permissible expression, but not what you are seeking. $\endgroup$ – Alan Dec 27 '16 at 6:49
6
$\begingroup$

You could always do this with ReplacePart although you have to reassign mat altogether:

In[50]:= mat = ReplacePart[mat, {{1, 1} -> a, {-1, -1} -> b}]

Out[50]= {{a, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, b}}
$\endgroup$
1
$\begingroup$

Also

indices = {{1, 1}, {-1, -1}};
vals = {a, b};

mat = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
(mat[[##]] = vals[[#]]) & @@@indices; mat

{{a, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, b}}

Or

mat = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
mat = Block[{i = 1}, MapAt[vals[[i++]] &, mat, indices]]; mat

{{a, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, b}}

Or

mat = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
(mat[[## & @@ #]] = #2) & @@@ Transpose[{indices, vals}]; mat

{{a, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, b}}

$\endgroup$

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.