Expert Answer:
:
There are several differences between a cell array and a matrix in MATLAB:
-
A cell array may contain any arbitrary type of element in each cell; while a matrix requires the types of its elements to be homogeneous i.e. of the same type.
-
As far as memory layout goes, all elements of a matrix are laid out contiguously in memory, while a cell array contains pointers to each element of the array. This can be important when considering things like cache locality for high performance code.
-
The flip side of point 2 is that when you resize a matrix every element in the matrix must be copied over to the newly allocated memory area, but in case of a cell array only a list of pointers needs to copied over. Depending on the size and type of elements you're storing, this might mean cell arrays are much faster to resize.
To illustrate the differences in memory layout, let's consider a simple example:
A = [10 20 30 40];
Here MATLAB creates a new matrix variable named A, allocates enough memory to hold 4 doubles (32 bytes, assuming 8 byte doubles) and assigns this memory to a pointer that points to the real part of A. (If you create a matrix of complex numbers, memory is allocated for the imaginary part also, and a separate pointer points to this memory area).
Now let's create a cell array that holds these elements:
B = cell(1, 4);
B{1,1} = 10;
B{1,2} = 20;
B{1,3} = 30;
B{1,4} = 40;
When MATLAB executes the first statement, it creates a cell array that contains 4 pointers, each of which can point to an arbitrary type. So B
is already using 16 bytes (assuming 32-bit pointers). The next line creates a 1x1 matrix containing the value 10 and assigns it to the first cell array element. The process here is similar to the one I described above for creation of a 1x4 matrix, except that the memory allocated is only large enough to hold one double (8 bytes). This is repeated for each of the remaining 3 statements. So, at the bare minimum, the second example uses 16 + 8 x 4 = 48
bytes.
Note that each variable in MATLAB also includes memory overhead for a structure called an mxArray that stores information such as dimension, data type and a lot more about that variable. I've ignored this overhead for the sake of simplicity.