0

I am trying to make this for loop pre allocated in matlab. I am having trouble transferring data from one array to another. Can someone help make this preallocated array

myArray = [] 
variableArray= []

 for i=1:10
 variable = [1,2,3]
 variableArray = [variable]
 myArray = [myArray variableArray]

end
r123456
  • 21
  • 5

2 Answers2

1

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.

Community
  • 1
  • 1
hbaderts
  • 14,136
  • 4
  • 41
  • 48
  • 2
    Your preallocation code snippet is not preallocating, you're still growing the array in size by concatenating `variable` onto the end of it in every iteration of the loop. – sco1 Apr 12 '15 at 12:38
  • @excaza Oh you are right of course, I had completely overlooked that. Thank you for your comment! – hbaderts Apr 12 '15 at 13:21
1

As pointed out by excaza as a comment in the other answer, here is the Modified for loop with pre-allocation

myArray = zeros(1,30);
for i=1:3:30
    variable = [1,2,3];
    myArray(i:i+2) = variable;
end

Else, you could use the approach with repmat as suggested by hbaderts in the other answer

Community
  • 1
  • 1
Santhan Salai
  • 3,888
  • 19
  • 29