What is the difference between cell (i.e. with { }) and matrix (i.e. with [ ]) in Matlab?
What is the difference between cell (i.e. with { } ) and matrix (i.e.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:
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
Bis already using 16 bytes (assuming 32-bit pointers).The next line creates a 1×1 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 1×4 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 = 48bytes.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.