MATLAB - 如何声明一个 "row slots"的矩阵供我插入行?

标签 matlab matrix

在每次迭代中,我将一行插入行号已预先确定的矩阵中。我当前的实现是

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 循环

之前预先分配一个 3×3 矩阵

我的矩阵 = zeros(3,3);

附言,
最好not to use i and j as variable names in Matlab .

关于MATLAB - 如何声明一个 "row slots"的矩阵供我插入行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22385156/

相关文章:

java - 如何检查 vector vector 中的位置是否超出范围?

python - 从python中的矩阵中提取列作为向量

c# - 如何实现二维矩阵的Kadane算法

matlab - 中轴骨架图

c++ - Matlab repmat 函数等价于 C++

performance - 在 MATLAB 中乘以标量的外积之和

matlab - 求槽的长度

matrix - 为什么在计算矩阵/多维数组的FFT时需要计算转置?

arrays - 将多个 channel 添加到 28x28x5000 矩阵

matlab - 相当于 R 中的 matlab 'ans'