When is it appropriate to use a cell array vs. a struct in Matlab?

CJS picture CJS · Sep 3, 2010 · Viewed 21.8k times · Source

If I want to store some strings or matrices of different sizes in a single variable, I can think of two options: I could make a struct array and have one of the fields hold the data,

structArray(structIndex).structField

or I could use a cell array,

cellArray{cellIndex}

but is there a general rule-of-thumb of when to use which data structure? I'd like to know if there are downsides to using one or the other in certain situations.

Answer

yuk picture yuk · Sep 3, 2010

In my opinion it's more a matter of convenience and code clarity. Ask yourself would you prefer to refer your variable elements by number(s) or by name. Then use cell array in former case and struct array in later. Think about it as if you have a table with and without headers.

By the way you can easily convert between structures and cells with CELL2STRUCT and STRUCT2CELL functions.