Matlab中生成列主序转行主序的置换矩阵技术问询
Generating the Permutation Matrix for Row-Major Order from Column-Major Vector in MATLAB
Got it, let's walk through how to create exactly the permutation matrix you need. The core idea is mapping the indices of a row-major flattened array back to their positions in a column-major flattened array, then building a matrix that swaps those positions.
Step-by-Step Explanation
For an m×n matrix M:
- Column-major flattening (
reshape(M, [], 1)) maps each elementM(r,c)to position(c-1)*m + rin the 1D vector. - Row-major flattening (equivalent to
reshape(M', [], 1)) maps each elementM(r,c)to position(r-1)*n + cin the 1D vector. - We need a permutation matrix
Pwhere multiplyingPby the column-major vector rearranges elements to match the row-major order. This means for each positioniin the row-major vector, we find which positionjit occupies in the column-major vector, then setP(i,j) = 1.
MATLAB Code Implementation
Here's the code that generates the permutation matrix for any m×n matrix:
% Define your matrix (example from your question) M = [1,2,3;4,5,6]; m = size(M, 1); % Number of rows n = size(M, 2); % Number of columns % Generate indices for the row-major flattened vector row_major_indices = 1:(m*n); % Calculate corresponding row (r) and column (c) in the original matrix for each row-major index r = floor((row_major_indices - 1)/n) + 1; c = mod(row_major_indices - 1, n) + 1; % Map these (r,c) positions to their column-major flattened indices col_major_positions = (c - 1)*m + r; % Initialize permutation matrix P = zeros(m*n); % Set the appropriate entries to 1 P(sub2ind(size(P), row_major_indices, col_major_positions)) = 1;
Verification with Your Example
Running this code with your M = [1,2,3;4,5,6] will produce exactly the matrix you provided:
P = 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
You can confirm it works by computing v1 = reshape(M, [], 1) and v2 = P*v1—you'll get v2 = [1;2;3;4;5;6], which matches the row-major order you want.
内容的提问来源于stack exchange,提问作者Ganesh Sundar




