How do I extract the odd and even rows of my matrix into two separate matrices and reconstruct it back using vectorized code?

278 views (last 30 days)
I would like to reconstruct my original matrix from the odd and even matrices using vectorized code.
I have a matrix M:
n = 7;
M = repmat((1:n)',1,5)
I split matrix M into two matrices. One contains the odd rows and another the even ones. Is it possible to reconstruct the initial matrix without using a FOR loop?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 17 Aug 2013
Here is an example on how to extract the odd and even rows of a matrix into two separate matrices:
n = 7; % number of rows
M = repmat((1:n)',1,5)
A = M(1:2:end,:) % odd matrix
B = M(2:2:end,:) % even matrix
To reconstruct the original matrix you can preallocate the result matrix and then use indexing similar to what was used above for splitting:
C = ones(size([A;B]))
C(1:2:end,:) = A
C(2:2:end,:) = B
As an alternative, you can use the SORT function to create an index for rearranging rows:
% concatenate odd and even matrices
C = [A;B] ;
% get odd row indices
oddI = 1:2:size(C,1) ;
% get even row indices
evenI = 2:2:size(C,1) ;
% concatenate odd and even row indices, then use SORT to find appropriate reordering
[~,reorderI] = sort([oddI,evenI])
% reorder matrix to reconstruct original matrix
M0 = C(reorderI,:)

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!