1
$\begingroup$

For example:

a = Range[20];
a = ArrayReshape[a, {4, 5}]

matrix a

I want to take elements from a with interval = 2 :

sublist of a

Take[a, {1, -1, 2}] fails to do this.

It would be better if it works for 3D or higher-dimensional large matrix.

$\endgroup$
  • $\begingroup$ Take[Partition[Range[20], 5], {1, -1, 2}, {1, -1, 2}] works, tho. Probably more generally: myTake[list_?ArrayQ] := Take[list, Sequence @@ ConstantArray[{1, -1, 2}, ArrayDepth[list]]]. (I don't have Mathematica on hand for testing.) $\endgroup$ – J. M. will be back soon May 2 '15 at 2:22
  • 2
    $\begingroup$ The way I'd do this is a[[;; ;;2, ;; ;; 2]] (look up Part and Span) $\endgroup$ – 2012rcampion May 2 '15 at 2:37
  • 1
    $\begingroup$ @2012rcampion yes, I found it in the basic examples. $\endgroup$ – novice May 2 '15 at 2:44
8
$\begingroup$

That is precisely what Downsample is for:

a = Range[20];
a = ArrayReshape[a, {4, 5}];
Downsample[a, 2]

(* {{1, 3, 5}, {11, 13, 15}} *)
$\endgroup$
  • $\begingroup$ That's neat: I've learned a new function today! Would it be correct to say, however, that its functionality can be reproduced entirely by the use of Part, like @2012rchampion showed in the comment to the original question? For instance a[[;; ;; 2, ;; ;; 3]] == Downsample[a, {2, 3} ]. Actually, using Part seems to me slightly more flexible, because different offsets can be specified for each direction (e.g. a[[ hoff ;; ;; 2, voff ;; ;; 3 ]], but maybe I misunderstand Downsample. The Downsample syntax is more readable than the Part specification though. $\endgroup$ – MarcoB May 2 '15 at 4:17
  • $\begingroup$ @Marc A quick test confirms that offset can be a list: Downsample[Partition[Range[20], 5], {2, 3}, {1, 2}] gives the expected result. $\endgroup$ – 2012rcampion May 2 '15 at 20:01
  • $\begingroup$ @2012rcampion I see. Thanks for checking! $\endgroup$ – MarcoB May 3 '15 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.