This is the prime example of a piece of code that should be vectorized can help you understand vectorization. Your code can be written like this:
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, []);
Explanation:
Let A
be a column vector (1 column, n
rows), and B
be a row vector (1 row, m
columns.
What bsxfun(@plus, A, B)
will do here is to add all elements in A
with all elements in B
, like this:
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)
Now, for the two vectors we have: zeros(n,1)
, and 0:reps
, this will give us;
0+0 0+1 0+2 0+reps
0+0 0+1 0+2 0+reps
% n rows of this
So, what we need to do now is place each column underneath each other, so that you will have the column with zeros first, then the row with ones, ... and finally the one with reps
(147 in your case).
This can be achieved by reshaping the matrix:
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
Another approach is using kron
:
kron(ones(reps+1, 1) * 0:(n-1)
For the record, a review of your code:
You should always preallocate memory for matrices that are created inside loops. In this case you know it will become a matrix of dimensions ((reps+1)*n-by-1)
. This means you should do Time = zeros((reps+1)*n, 1);
. This will speed up your code a lot.
You shouldn't use i
and j
as variable names in Matlab, as they denote the imaginary unit (sqrt(-1)
). You can for instance do: for ii = 1:(n*147)
instead.
You don't want c=i
inside the loop, when the loop is supposed to go from c to c + 146. That doesn't make much sense.