ImbaBalboa
ImbaBalboa

Reputation: 867

cell array of cell array in a structure MATLAB

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

Upvotes: 0

Views: 81

Answers (1)

zeeMonkeez
zeeMonkeez

Reputation: 5157

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)})

Upvotes: 1

Related Questions