将矩阵转换为矢量

时间:2015-06-29 06:34:41

标签: matlab matrix vector

我有一个矩阵。我想从矩阵中获取一个向量,如下例所示:

Matrix = [ 2  4  5; 
           8  2  13; 
           0  3  1; 
           7  7  7; 
           36 62 72; 
           44 35 26;
           63 11 4;
           9  9  9 ];

vector = [ 2 8 0 4 2 3 5 13 1 7 36 44 63 62 35 11 72 26 4 9];

向量插入每列前三行的每个值。然后它插入第四行值一次。然后,对矩阵中的其余元素重复该过程。如何在Matlab中做到这一点?

1 个答案:

答案 0 :(得分:0)

你的问题非常具体。除了你自己,我不知道这对任何人有什么用处。 没有“一线解决方案”。 有很多方法可以处理索引问题,我喜欢在可能的情况下使用标量索引:

Ncolumns = size(Matrix,1);
Nblocks = floor(Ncolumns/4);                                  %number of 4-line blocks (excluding the last block if it is not a full 4-lines)
IndexVector = (1:3)'*ones(1,3) + ones(3,1)*(0:2) * Ncolumns; %this gives 3 lines as specified.
IndexVector = [IndexVector(:); 4];                           %this adds the first element of 4th line, as spec.
IndexVector = IndexVector*ones(1,Nblocks)+ones(10,1)*(0:Nblocks-1)*4; %this repeats the above for rest of blocks.
IndexVector = IndexVector(:)';                               %make row vector

vector=Matrix(IndexVector);

if mod(Ncolumns,4)                               %this deals with the last partial block
   subMat=Matrix(Nblocks*4+1:end,1:3);
   vector=[vector subMat(:)']; 
end    
相关问题