I have a 2D array in Matlab that needs to be converted to 1D, and Matlab uses column major representation for the conversion. However, I'd like to use a doubly stochastic matrix to convert the representation to row major.
For example, I have the following 2D array:
M = [1,2,3;4,5,6]
If I use reshape to represent it in 1D
v1 = reshape(M,size(M,1)*size(M,2),1)
I get a column major representation:
v1 = [1,4,2,5,3,6]
However, I'd like to use a permutation matrix like this:
A = [1,0,0,0,0,0;
0,0,1,0,0,0;
0,0,0,0,1,0;
0,1,0,0,0,0;
0,0,0,1,0,0;
0,0,0,0,0,1];
so that I get the following row major representation:
v2 = [1,2,3,4,5,6]'
by doing
v2 = A*v1
I know that I can get v2 by just doing
v2 = reshape(M',size(M,1)*size(M,2),1)
But I am particular about generating the permutation matrix in order to convert to row major representation.
If someone could help me generate this permutation matrix, it would really help. Thanks in advance!
You can create your matrix
Ausing linear indexing. Elements in a matrix can be indexed with one index, they are then addressed column-wise, in the same order in which they appear when reshaping the matrix to a vector.You need to set an element in each odd column, where the element is one down from the previous column:
And also one in each even column in a similar way:
This works for all matrices
Mwith two rows. For a matrix withmrows:If the line that requires newer version of MATLAB gives you an error, replace with
bsxfun(@plus,index,offset').