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

203 次查看(过去 30 天)
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?

采纳的回答

MathWorks Support Team
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,:)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by