Search code examples
arraysmatlabcell-array

How to create a dynamic array in MATLAB


Description of this array:

  • 10 dimensions, which represent 10 clusters.
  • Each dimension's length is not fixed, and should be zero at first.
  • After clustering, one coordinate (x,y) will be assigned to the corresponding cluster.

Example:

If (1,1) belongs to cluster 10, (2,2) belongs to cluster 9, and given a sequence of coordinates

(1,1) (1,1) (1,1) (1,1) (1,1) (2,2)

then A(1) to A(8) have no element while A(9) has 1 element with value (2,2) and A(10) has 5 elements with value (1,1).


I tried to use cell array, and I "kind of" get one, here is my code.

A = cell(10,0) 
%create empty cell array
A(10,end+1) = {[1,1]} 
%assign (1,1) to cluster 10

So now A is:

A

Then suppose we have (2,2) and it should assigned to A(9)

A(9,end) = {[2,2]}

A9

Looks fine, but then if we assign (1,1) to A(10) again,

A(10,end) = {[1,1]}

A3

Then the length is still the same and A(1) to A(8) are not empty!

My question is, is there any other method that can help me to create a dynamic array?


Solution

  • In MATLAB, we'll often store multiple coordinates into a single array, such that p(3,:) is the 3rd point. [One of the reasons for this is that this is a much more efficient way of storing data, as each array has an overhead, and storing many points as individual arrays within a e.g. cell array therefore is very wasteful of memory.]

    I would suggest you use that method to store coordinates within each cluster. For example:

    A = cell(10,1); % 10 clusters, we won't change the size of A
    A{10}(end+1,:) = [1,1]; 
    A{9}(end+1,:) = [2,2];
    A{10}(end+1,:) = [1,1];
    

    Now we can see what is inside A:

    >> A{1}
    ans =
         []
    
    >> A{9}
    ans =
         2     2
    
    >> A{10}
    ans =
         1     1
         1     1
    

    Note that A{10} is the contents of the cell (in this case a numeric array), whereas A(10) is a cell array with one cell.

    A{10}(1,:) is the first coordinate in cluster 10. size(A{10},1) is the number of coordinates in cluster 10.

    A{10}(end+1,:) = [1,1] is one way of appending an element. end+1 is a non-existing location, meaning the array will be extended to accommodate the new data assigned there. An alternative method is A{10} = [A{10} ; 1,1]. I'm not sure if these two methods are equivalent or not. In the case of a vector, or when appending a column, then the end+1 method is much more efficient, so I always recommend that method in all cases.