# How to extract the first and last element

It is a elemental question maybe,but I am confusing still.If I have a 1-dimension list list

a = Range
(* {1, 2, 3, 4, 5} *)


So I can do this to get the first and last element:

a[[{1, -1}]]
(* {1, 5} *)


But when I have a matrix mat,why I cannot do this with same method?

mat = Partition[Range, 4];
mat[[{{1, 1}, {-1, -1}}]]


This expression will put some error information.

### Question

1. Did I make any grammatical mistakes?
2. Can we use any elegant method to get this two elements?
• You can use Extract with similar syntax, I believe. – march Dec 27 '16 at 4:25
• You can use mat[[1,1]] and mat[[-1,-1]]. Or to use same syntax as 1D example, can Flatten the matrix first. – Nasser Dec 27 '16 at 4:28
• @march Good point out,just little pitty,we cannot asign it by same syntax Extract[mat,{{1,1},{-1,-1}}]={c,d}.This is my purpose actually. – yode Dec 27 '16 at 4:28
• @Nasser Thanks advice,which is a good suggestion. – yode Dec 27 '16 at 4:31
• I find using [[x,y]] much easier and more common with other languages (Matlab, etc...) than having to call functions to do it – Nasser Dec 27 '16 at 4:31

## 1 Answer

Does the following help:

mat = Partition[Range, 4];
{#[[1, 1]], #[[-1, -1]]} & @ mat


Or, alternatively,

{First@First@#, Last@Last@#} & @ mat

• suspect you are looking for something different than the following. mat[[1, 1]] = a; mat[[-1, -1]] = b; mat // TableForm – user6546 Dec 27 '16 at 4:42
• @Thanks, :)If we just extract,we can use {First@#, Last@#} &@Flatten[mat] or Through[{First,Last}[Flatten[mat]]] – yode Dec 27 '16 at 5:14