将矩阵转换为沿其对角线的矢量

use*_*141 9 algorithm matlab transform matrix

我不是一个程序员,我只需要在matlab中以数字方式解决问题.我需要一个函数来对任何方阵进行以下转换:

row 1: 1 2 3 
row 2: 4 5 6
row 3: 7 8 9
Run Code Online (Sandbox Code Playgroud)

1 4 2 7 5 3 8 6 9
Run Code Online (Sandbox Code Playgroud)

即从左到右依次沿着对角线在矢量中写入矩阵.有什么想法吗?


我真的需要一些帮助:

假设我们已经转换为向量的矩阵具有由M(i,j)表示的条目,其中i是行和j列.现在我需要能够从向量中的位置找出矩阵中的原始位置,即如果它在向量中的第3个条目,我需要一个能给我i = 1 j = 2的函数.有什么想法吗?我真的坚持这个:(谢谢

Amr*_*mro 6

这与以前以Z字形顺序遍历矩阵的问题非常相似.稍作修改,我们得到:

A = rand(3);                        %# input matrix

ind = reshape(1:numel(A), size(A)); %# indices of elements
ind = spdiags(fliplr(ind));         %# get the anti-diagonals
ind = ind(end:-1:1);                %# reverse order
ind = ind(ind~=0);                  %# keep non-zero indices
B = A(ind);                         %# get elements in desired order
Run Code Online (Sandbox Code Playgroud)

使用SPDIAGS功能.这样做的好处是它适用于任意矩阵大小(不仅仅是方形矩阵).例:

A =
      0.75127      0.69908      0.54722      0.25751
       0.2551       0.8909      0.13862      0.84072
      0.50596      0.95929      0.14929      0.25428
B =
  Columns 1 through 6
      0.75127       0.2551      0.69908      0.50596       0.8909      0.54722
  Columns 7 through 12
      0.95929      0.13862      0.25751      0.14929      0.84072      0.25428
Run Code Online (Sandbox Code Playgroud)


Jon*_*nas 3

这是执行此操作的一种方法。

%# n is the number of rows (or cols) of the square array
n = 3;
array = [1 2 3;4 5 6;7 8 9]; %# this is the array we'll reorder

%# create list of indices that allow us
%# to read the array in the proper order
hh = hankel(1:n,n:(2*n-1)); %# creates a matrix with numbered antidiagonals
[dummy,sortIdx] = sort(hh(:)); %# sortIdx contains the new order

%# reorder the array
array(sortIdx)

ans =
     1     4     2     7     5     3     8     6     9
Run Code Online (Sandbox Code Playgroud)