这是一段代码的主要例子,应该是vectorized可以帮助你理解vectorization。你的代码可以这样写:
n = 147;
reps = 10; %% Replace this by the maximum number you want your matrix to have
Time = reshape(bsxfun(@plus, zeros(n,1), 0:reps), 1, []);
说明:
设A 为列向量(1 列,n 行),B 为行向量(1 行,m 列。
bsxfun(@plus, A, B) 在这里要做的是将A 中的所有元素与B 中的所有元素相加,如下所示:
A(1)+B(1) A(1)+B(2) A(1)+B(3) ... A(1)+B(m)
A(2)+B(1) A(2)+B(2) ............. A(2)+B(m)
............................................
A(n)+B(1) A(n)+B(2) .............. A(n)+B(m)
现在,对于我们拥有的两个向量:zeros(n,1) 和 0:reps,这将给我们;
0+0 0+1 0+2 0+reps
0+0 0+1 0+2 0+reps
% n rows of this
所以,我们现在需要做的是将每一列放在彼此的下方,这样一来,您将首先获得带有 0 的列,然后是带有 1 的行,...最后是带有 reps 的行(147 in你的情况)。
这可以通过reshaping矩阵来实现:
reshape(bsxfun(@plus, zeros(n,1), 0:reps), [], 1);
^ ^ ^ ^
| | | Number of rows in the new matrix. When [] is used, the appropriate value will be chosen by Matlab
| | Number of rows in the new matrix
| matrix to reshape
reshape command
另一种方法是使用kron:
kron(ones(reps+1, 1) * 0:(n-1)
作为记录,对您的代码进行审查:
您应该始终为循环内创建的矩阵预先分配内存。在这种情况下,您知道它将成为维度矩阵((reps+1)*n-by-1)。这意味着你应该做Time = zeros((reps+1)*n, 1);。这将大大加快您的代码速度。
您不应该在 Matlab 中使用 i 和 j 作为变量名,因为它们表示虚数单位 (sqrt(-1))。例如,您可以这样做:for ii = 1:(n*147)。
当循环应该从 c 转到 c + 146 时,您不希望 c=i 在循环内。这没有多大意义。