3
$\begingroup$

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

a = Range[5]
(* {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[12], 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?
$\endgroup$
6
  • $\begingroup$ You can use Extract with similar syntax, I believe. $\endgroup$
    – march
    Dec 27, 2016 at 4:25
  • $\begingroup$ You can use mat[[1,1]] and mat[[-1,-1]]. Or to use same syntax as 1D example, can Flatten the matrix first. $\endgroup$
    – Nasser
    Dec 27, 2016 at 4:28
  • $\begingroup$ @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. $\endgroup$
    – yode
    Dec 27, 2016 at 4:28
  • $\begingroup$ @Nasser Thanks advice,which is a good suggestion. $\endgroup$
    – yode
    Dec 27, 2016 at 4:31
  • $\begingroup$ I find using [[x,y]] much easier and more common with other languages (Matlab, etc...) than having to call functions to do it $\endgroup$
    – Nasser
    Dec 27, 2016 at 4:31

1 Answer 1

3
$\begingroup$

Does the following help:

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

Or, alternatively,

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

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.