7

I have a matrix in MATLAB from which I want to sample every other entry:

a =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

And I want:

result =

     1     9    
     3    11    

How can I do this without a for loop?

gnovice
  • 125,304
  • 15
  • 256
  • 359
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319

4 Answers4

12

I don't know of a multi-dimensional way to do it automatically, but Matlab's indexing is good enough if you're happy to specify it for each dimension:

a(1:2:end,1:2:end)
Will Robertson
  • 62,540
  • 32
  • 99
  • 117
5

This should work for your specific example:

result = a([1 3],[1 3]);

and more generally:

result = a(1:2:size(a,1),1:2:size(a,2));

For more details about indexing in MATLAB, you can check out the documentation here.

gnovice
  • 125,304
  • 15
  • 256
  • 359
2

I found this today. A is the original matrix, sampled every s element.

Adown=downsample(downsample(A,s)',s)'

It down-samples the matrix vertically, transposes, then samples the orthogonal direction, then transposes back.

Mike
  • 21
  • 1
1
samples_x = floor(linspace(1, size(a,1), new_Nx));
samples_y = floor(linspace(1, size(a,2), new_Ny));
new_a = a(samples_x,samples_y)
rocky
  • 11
  • 1
  • +1 and welcome to Stack Overflow! Your answer could be even more useful if you explained in a few words what your code does. Feel free to use the edit link below your question... – Jonas Heidelberg Nov 02 '11 at 21:25