You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

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:

  1. Column-major flattening (reshape(M, [], 1)) maps each element M(r,c) to position (c-1)*m + r in the 1D vector.
  2. Row-major flattening (equivalent to reshape(M', [], 1)) maps each element M(r,c) to position (r-1)*n + c in the 1D vector.
  3. We need a permutation matrix P where multiplying P by the column-major vector rearranges elements to match the row-major order. This means for each position i in the row-major vector, we find which position j it occupies in the column-major vector, then set P(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

火山引擎 最新活动