As @Daniel mentionned in comments, the second line
variableArray = [variable];
does nothing at all and can be dumped.
What you do in the for loop is concatenate 10 vectors of size 1x3
. The resulting vector will therefore be 1x30
. This can be verified by getting the size after running your code:
size(myArray)
ans =
1 30
To preallocate this vector, you can create a vector of zeros which has this size:
myArray = zeros(1,30);
You can then chose to either iterate through from 1
to 30
in steps of 3
, as suggested by @Santhan Salai in his answer, or go from 1
to 10
as before and use logical indexing to write the variable
to the correct place, like I am demonstrating in the following snippet:
myArray = zeros(1,30);
for k=1:10
variable = [1,2,3];
myArray(3*(k-1)+1:3*k) = variable;
end
Note that I changed the loop variable from i
to k
, as i
is used as the imaginary unit in MATLAB and should not be used as variable (see this question for details).
You can actually also dump the for loop and do this with the repmat
function, which needs no loop and no preallocation:
myArray = repmat([1,2,3],1,10);
which replicates the vector [1,2,3]
10 times.