What is the difference between cell and matrix in Matlab?

原文链接

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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值