【问题标题】:Convert Matrix to Vector [closed]将矩阵转换为向量 [关闭]
【发布时间】:2015-09-15 12:47:21
【问题描述】:

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

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 中做到这一点?

【问题讨论】:

  • 你如何看待 reshape 和 for 循环?无论如何,你应该展示你到目前为止所做的尝试。这样做,我和你将有更好的机会在这里获得帮助。
  • 您的描述说您正在以某种方式重新排序元素,但矩阵和向量包含不同的元素。
  • 我尝试重塑矩阵,但它不起作用。
  • 是的,如上面示例中所述,存在重新排序。矩阵和向量中的元素是相同的。我已经在 Matlab 工作区中检查了它们。
  • 矩阵为8x3,向量的期望输出为1x20。

标签: matlab matrix vector


【解决方案1】:

您的问题是一个非常具体的问题。我看不出这对除了你自己以外的任何人有什么用处。 没有“单线解决方案”。 有很多方法可以解决索引问题,我喜欢尽可能使用标量索引:

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    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 2021-04-29
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多