0

I'm trying to have a cell array of cell array in order to store data in a structure.

Here is my example :

close all;
clear all;
clc;

register = struct('thing', [], ...
                  'positions', cell(1));

register.positions{1}{end+1} = {[45 36]};
register.positions{2}{end+1} = {[12 87]};

register

I got this following error message :

Cell contents reference from a non-cell array object.

Error in test (line 8) register.positions{1}{end+1} = {[45 36]};

I am definitely doing something wrong, but I have unsuccessfully tried many other things.

Thank you for your help

ImbaBalboa
  • 851
  • 9
  • 23
  • 2
    What would the desired result be? – Luis Mendo Dec 12 '15 at 00:02
  • Of course I could do another way (An array of struct), but I thought that was a good idea to have all my data in one structure. Actually, I want to have an attribute of my structure which can contain dynamic cell array of a dynamic cell array of coordinates. – ImbaBalboa Dec 12 '15 at 00:09
  • For instance, I have 2 cars, and for each cars I received positions. My first car could have five different coordinates and my second only 2 coordinates. That's why I need to use cell arrays cause I don't know the size of my arrays. – ImbaBalboa Dec 12 '15 at 00:12
  • So why not have a `register` struct (of length number of 'cars') with a field `positions` which is a cell that contains your coordinates? – Tom Dec 12 '15 at 00:15
  • Juste because I would like to know if it was possible to do this way. I have also seen on that post [link](http://stackoverflow.com/questions/4166438/how-do-i-define-a-structure-in-matlab/4169216#4169216) that an array of structs is more resourceful in term of memory than a structure of arrays. – ImbaBalboa Dec 12 '15 at 00:21

1 Answers1

1

The cell has to be initialized first. Let's break it up: Your code

register = struct('thing', [], 'positions', cell(1));

actually creates a structure with two empty fields:

>> register

register = 

    thing: []
positions: []

Assigning directly using end (e.g. with register.positions{1}{end+1}=4) will fail, because end in the second level will try to determine the size of the cell at register.positions{1}, but register.positions itself is empty!

So, what do we do? We could ensure that at the first time a new element at the top level is referred to, we initialize it without referring to its content. For example, register.positions{1} = [] will do the job, and

register.positions{1}{end+1} = [45 36];

will then work. (Note: here I have not encapsulated the array in another set of curly braces, because from your comments above it seems they're not necessary.)

Now, to make this a bit more convenient, you preallocate the positions field with the number of elements ('cars' in your comment), if it is known (or a number larger than expected):

register = struct('thing', [], 'positions', {cell(1, 42)})
zeeMonkeez
  • 5,057
  • 3
  • 33
  • 56