Get even/odd indices of a matrix - MATLAB

DrSkyer picture DrSkyer · Oct 27, 2014 · Viewed 24.3k times · Source

I have following problem:

I have a given matrix of let's say 4x4. How can I get the indices of the following combinations:

  • row odd and column odd
  • row odd and column even
  • row even and column odd
  • row even and column even

For example if I have the matrix:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
  • 'row odd and column odd' would be the indices of 1, 3, 9, 11...
  • 'row odd and column even' would be the indices of 2, 4, 10, 12...
  • 'row even and column odd' would be the indices of 5, 7, 13, 15...
  • and 'row even and column even' would be indices of 6, 8, 14, 16...

Also, is it possible to combine those operations so e.g. I get the indices for 'row odd and column odd' and 'row even and column even'?

Thank you!

Answer

rayryeng picture rayryeng · Oct 27, 2014

It's pretty easy to do with indexing:

Odd rows and odd columns

B = A(1:2:end, 1:2:end);

Odd rows and even columns

B = A(1:2:end, 2:2:end);

Even rows and odd columns

B = A(2:2:end, 1:2:end);

Even rows and even columns

B = A(2:2:end, 2:2:end);

The above assumes that you want the actual matrix values themselves. It's a bit confusing as your matrix elements are the same as linear indexing values themselves. If you want to determine the actual column major indices to access the matrix, you can generate a vector from 1 to N where N is the total number of elements in your matrix, then reshape this matrix into the desired size that you want. After, use the same logic above to get the actual linear indices:

N = numel(A);
B = reshape(1:N, size(A,1), size(A,2));
ind = B(1:2:end, 1:2:end); %// For odd rows, odd columns
%// Repeat for the other ones...

Now, given your comment, you want to create a new matrix that will store only these extracted matrix values while making all of the other elements zero. If you want to do this, simply pre-allocate a matrix of zeroes, then copy over those values to extract using the computed indices into the new matrix. In other words:

N = numel(A);
B = reshape(1:N, size(A,1), size(A,2));
ind = B(1:2:end, 1:2:end); %// For odd rows, odd columns - Change to suit your tastes
out = zeros(size(A));
out(ind(:)) = A(ind(:));

If you want to combine the indices like having odd row - odd column, and even row - even column, just compute two sets of indices, concatenate them into a single vector and do the same syntax like before. Therefore:

N = numel(A);
B = reshape(1:N, size(A,1), size(A,2));
ind = B(1:2:end, 1:2:end); %// For odd rows, odd columns
ind2 = B(2:2:end, 2:2:end); %// For even rows, even columns
ind = [ind(:); ind2(:)];
out = zeros(size(A));
out(ind) = A(ind);