2
$\begingroup$

Let we have $(2\cdot r+1) \times (2\cdot r+1)$ matrix mat.
Is there a better way to extract it's central element,
rather than mat[[⌈Length@mat/2⌉, ⌈Length@mat/2⌉]]?

$\endgroup$
1
  • 5
    $\begingroup$ If you've already created a parameter r for the matrix dimensions and used it as you indicate, then all you need is mat[[r,r]]. I expect you knew that, I only make the comment for the benefit of complete neophytes. $\endgroup$ Commented Jul 27 at 15:12

1 Answer 1

4
$\begingroup$

Assuming "better way" means better performance: Since you know the matrix has odd dimensions, you can skip Floor. Furthermore, you can calculate the index just once. Implementing both of these runs ~30 % faster on my computer.

r = 10000;
mat = RandomReal[1, {2 r + 1, 2 r + 1}];

t1 = First@RepeatedTiming[mat[[⌈Length@mat/2⌉, ⌈Length@mat/2⌉]]]
(* 1.05714*10^-6 *)

t2 = First@RepeatedTiming[mat[[(Length@mat + 1)/2, (Length@mat + 1)/2]]]
(* 8.66862*10^-7 *)

t3 = First@RepeatedTiming[With[{m = (Length@mat + 1)/2}, mat[[m, m]]]]
(* 7.5219*10^-7 *)

1 - t3/t1
(* 0.288469 *)
$\endgroup$
1
  • $\begingroup$ Thank you! "Better way" means firstly syntactic sugar like TakeDrop or ListConvolve But as I see it, there’s nothing like that. So performance comes first and t3 is a very good idea! $\endgroup$
    – lesobrod
    Commented Jul 27 at 17:10

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.