何时使用数组以及何时使用单元阵列? [英] When to use array and when to use cell array?

查看:172
本文介绍了何时使用数组以及何时使用单元阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Matlab中,我试图把匿名函数在一个数组:

In Matlab, I was trying to put anonymous functions in an array:

>> a=[@(k)0.1/(k+1)    @(k)0.1/(k+1)^0.501]
??? Error using ==> horzcat
Nonscalar arrays of function handles are not allowed; use cell arrays
instead.

所以,我不知道什么种元素的数组是允许的,并且在单元阵列?

So I wonder what kinds of elements are allowed in an array, and in a cell array?

例如,我知道,在一个数组,该元素可以是数值或字符串。还有什么呢?

For example, I know that in an array, the elements can be numerical or strings. What else?

推荐答案

总之:单元阵列一个的异构的容器,定期阵列的均匀。这意味着,在一个规则阵列的所有元素是同一类型的,而在单元阵列,它们可以是不同的。你可以阅读更多关于单元阵列<一个href=\"http://stackoverflow.com/questions/9055015/difference-between-accessing-cell-elements-using-and-curly-or-normal-brac/9055336#9055336\">here.

In short: Cell array is a heterogeneous container, regular array is homogeneous. This means that in a regular array all of the elements are of the same type, whereas in cell array, they can be different. You can read more about cell array here.

使用单元阵列时:


  • 您有不同类型的数组中

  • 您不能确定是否在未来可能会扩展到其他类型的

  • 您与该有遗传模式对象工作

  • 您与字符串数组工作 - 几乎任何场合是preferable到的 CHAR(N,M)

  • 您有一个大阵,你经常更新功能的单个元素 - 由于Matlabs的写入时复制的策略

  • 您与函数处理工作(如@Pursuit解释)

preFER 规则排列时:


  • 的所有元素都具有相同的类型

  • 您正在更新一次性全阵列式 - 像数学运算

  • 您想拥有类型安全

  • 您不会改变阵列的数据类型在未来

  • 您与数学矩阵的工作。

  • 您与不具有继承对象时

有关的更多解释写入时复制的:

当你传递一个数组给一个函数,指针/引用传递。

When you pass an array to a function, a pointer/reference is passed.

function foo(x)
     disp(x);
end

x= [1 2 3 4 5];
foo(x); %No copy is done here! A pointer is passed.

但是,当你改变它(或它的一部分),将创建一个副本。

But when you change it (or a part of it), a copy is created.

function foo(x)
    x(4) = x(4) + 1;
end

x= [1 2 3 4 5];
foo(x); %x is being copied! At least twice memory amount is needed.

在一个单元阵列中,只有细胞复制。

In a cell array, only the cell is copied.

function foo(x)
   x{4} = x{4} + 1;
end

x= {1 2 3 4 5}; %Only x{4} will be copied

因此​​,如果你把那个叫大阵上改变单一元素的功能,你赚了很多拷贝 - 这使得它更慢。但是,在一个单元阵列,它不是这样的。

Thus, if you call a function that changes a single element on a large array, you are making a lot of copies - that makes it slower. But in a cell array, it is not the case.

这篇关于何时使用数组以及何时使用单元阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆