【发布时间】: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 的矩阵。
【问题讨论】: