Search code examples
arrayslistmatlabpolylinecell-array

Non-empty size information for cell arrays


In MATLAB I would like to keep a list of polylines - containing vertices (x,y) - in a container and I thought the best idea is to use cell arrays for this task. Each line would be represented in a row in a cell array, with vertices (x,y) being the elements of the cells. The different lines would be of different length, that's why I thought it would be a good idea to use cell arrays.

My problem however is that I don't know how can I append to the first non-empty element of each row in a cell-array?

Here is an example:

cell{1,1} = 1
cell{2,1} = 2
cell{3,1} = 3
cell{2,2} = 4
cell{2,3} = 5

cell =

    [1]     []     []
    [2]    [4]    [5]
    [3]     []     []

For example now I want to append a new element to the end of row 1, and another one to row 2. How do I know what is the first position where I can append a new element?

Or shell I use cell arrays inside cell arrays for this task?

How would you implement a container for a list of polylines MATLAB?


Solution

  • This is a bad way to store your data, for the very problems you're encountering. A couple notes:

    1. The first column is used as an index (i.e. 1 for polyline 1, 2 for polyline 2, etc.), which is unnecessary since that info is already stored implicitly in the structure of your data.
    2. With this method, points will have to be stacked next to each other, which will be a nightmare for indexing.
    3. With each x and y in a different cell, it's going to be an unneeded hassle to plot/store even a single point.

    There are 2 good ways to store all this information.

    1. Cell array: Like Clement pointed out, this is nice and simple, and will let you stack different points in the same polyline along a second dimension.

      celldata = {[] [4 5] []};
      celldata{2} = [celldata{2}; 1 1];
      celldata{3} = [0.5 0.5];
      
      >> celldata
      
      celldata = 
      
           []    [2x2 double]    [1x2 double]
      
    2. Structure array: This is a nice way to go if you want to store polyline-level metadata along with your points.

      strucdata = struct('points', {[] [4 5] []}, 'info', {'blah', 'blah', 'blah'});
      strucdata(2).points = [strucdata(2).points; 1 1];
      strucdata(3).points = [0.5 0.5];
      
      >> strucdata
      
      strucdata = 
      
      1x3 struct array with fields:
          points
          info
      
      >> strucdata(2)
      
      ans = 
      
          points: [2x2 double]
            info: 'blah'