将向量重塑为具有任意 m 和 n 的更大矩阵
Reshaping a vector into a larger matrix with arbitrary m and n
我正在尝试创建一个函数,该函数接受任意长度的向量并使用其条目生成大小为 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
然而,这仅适用于乘以小于或等于 'Vector' 中条目数两倍的 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 的矩阵。
你只需要
- 使用“modular”基于 1 的索引对向量进行索引;
- reshape it taking into account that Matlab is column-major,所以你需要交换
m
和n
;
- transpose 交换
m
和 n
。
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
我正在尝试创建一个函数,该函数接受任意长度的向量并使用其条目生成大小为 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
然而,这仅适用于乘以小于或等于 'Vector' 中条目数两倍的 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 的矩阵。
你只需要
- 使用“modular”基于 1 的索引对向量进行索引;
- reshape it taking into account that Matlab is column-major,所以你需要交换
m
和n
; - transpose 交换
m
和n
。
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