在每次迭代中,我将一行插入行号已预先确定的矩阵中。我当前的实现是
seqToBePutIntoMatrix = [1 2 3 4 5 6 7 8 9];
col_no = 3; % hence the matrix is 3x3
myMatrix = [];
for i = 1:col_no:length(seqToBePutIntoMatrix)
myMatrix = [myMatrix; seqToBePutIntoMatrix(i:i+col_no-1)];
end
MATLAB 向我建议
The variable
myMatrix
appears to change size in every loop iteration. Consider preallocation for speed.
我正在认真考虑它的建议,并希望预分配这样一个 3 行的空矩阵,并在每次迭代中插入一行。我试过这个:
seqToBePutIntoMatrix = [1 2 3 4 5 6 7 8 9];
col_no = 3; % hence the matrix is 3x3
myMatrix = [];
j = 1;
for i = 1:col_no:length(seqToBePutIntoMatrix)
myMatrix(j) = seqToBePutIntoMatrix(i:i+col_no-1);
j = j+1;
end
但是,这是行不通的。我怎样才能让它发挥作用?
最佳答案
下标 myMatrix(j)
仅引用 myMatrix
的一个单个 元素。为了引用整行,您需要
myMatrix(j,:) = seqToBePutIntoMatrix(i:i+col_no-1);
此外,您需要在 开始 for
循环
我的矩阵 = zeros(3,3);
关于MATLAB - 如何声明一个 "row slots"的矩阵供我插入行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22385156/