我有一个关于使用for循环从向量创建矩阵的简单问题,例如
A = [1:101];
matrix = [1 2 3 4 ... 50;
51 52 53 54 ... 100;
101 1 2 4 ... 49;
50 51 52 53 ... 100]
有人可以告诉我该怎么做吗?非常感谢
答案 0 :(得分:1)
我假设除了A
之外,你还有matrix
的行数和列数作为输入,即
A = 1:101;
nRows = 4;
nCols = 50;
试试这个:
% initialize
matrix = zeros(nCols, nRows); % create it transposed because we'll have to transpose it later because MATLAB is column-major
%figure out how many times we will have to repeat A
nRepeat = ceil(numel(matrix)/numel(A));
% Tile A
A_tiled = repmat(A, 1, nRepeat);
%fill in matrix
matrix(1:end) = A_tiled(1:numel(matrix));
%Finally, transpose
matrix = matrix';
返回
matrix = [1 2 3 4 ... 50;
51 52 53 54 ... 100;
101 1 2 4 ... 49;
50 51 52 53 ... 99]
尽可能接近
答案 1 :(得分:0)
它需要使用循环吗?
A= [1 2 3 4 ... 1000];
numberOfColumns = 3;
[matrix,padded] = vec2mat(A,numberOfColumns)
输出:
1 2 3
. . .
998 999 1000