# How to change the first value and last value in a matrix

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.

• list[[1, 1]] = a; list[[-1, -1]] = b keep it simple :) – Nasser Dec 27 '16 at 4:49
• (list[[Sequence @@ First@#]] = Last@#) & /@ {{{1, 1}, a}, {{-1, -1}, b}}; list – Edmund Dec 27 '16 at 4:50
• @Nasser Thanks. :) – yode Dec 27 '16 at 4:51
• @Edmund Thanks,too :) – yode Dec 27 '16 at 4:53
• 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. – Alan Dec 27 '16 at 6:49

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}}


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}}