【问题标题】:Reshaping a vector into a larger matrix with arbitrary m and n将向量重塑为具有任意 m 和 n 的更大矩阵
【发布时间】:2020-01-17 15:34:18
【问题描述】:

我正在尝试创建一个函数,该函数采用任意长度的向量并使用其条目来生成大小为 mxn 的矩阵,其中 m 和 n 是任意数字。如果矩阵具有比原始向量更多的条目,则条目应该重复。例如。一个向量 (1,2,3,4) 将构成一个 3x3 矩阵 (1,2,3;4,1,2;3,4,1)。

到目前为止我有这个功能:

function A = MyMatrix(Vector,m,n)

A = reshape([Vector,Vector(1:(m*n)-length(Vector))],[m,n]);

end

在某些情况下是成功的:

>> m=8;n=5;Vector=(1:20);
>> A = MyMatrix(Vector,m,n)

A =
     1     9    17     5    13
     2    10    18     6    14
     3    11    19     7    15
     4    12    20     8    16
     5    13     1     9    17
     6    14     2    10    18
     7    15     3    11    19
     8    16     4    12    20

但是,这仅适用于 m 和 n 的值乘以小于或等于“向量”中条目数的两倍的数字,因此在这种情况下为 40。当 mn 大于 40 时,此代码产生:

>> m=8;n=6;Vector=(1:20);
>> A = MyMatrix(Vector,m,n)
Index exceeds the number of array elements (20).

Error in MyMatrix (line 3)
A = reshape([Vector,Vector(1:(m*n)-length(Vector))],[m,n]);

我尝试使用诸如repmat 之类的函数来创建解决方法,但是,到目前为止,我还无法创建具有更大 m 和 n 的矩阵。

【问题讨论】:

    标签: matlab matrix reshape


    【解决方案1】:

    你只需要

    V = [10 20 30 40 50 60]; % vector
    m = 4; % number of rows
    n = 5; % number of columns
    A = reshape(V(mod(0:m*n-1, numel(V))+1), n, m).';
    

    这给了

    A =
        10    20    30    40    50
        60    10    20    30    40
        50    60    10    20    30
        40    50    60    10    20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多