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⌉]]
?
1 Answer
$\begingroup$
$\endgroup$
1
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 *)
-
$\begingroup$ Thank you! "Better way" means firstly syntactic sugar like
TakeDrop
orListConvolve
But as I see it, there’s nothing like that. So performance comes first andt3
is a very good idea! $\endgroup$– lesobrodCommented Jul 27 at 17:10
r
for the matrix dimensions and used it as you indicate, then all you need ismat[[r,r]]
. I expect you knew that, I only make the comment for the benefit of complete neophytes. $\endgroup$