MATLAB中的连接细胞阵列

发布于 2025-01-31 23:43:55 字数 187 浏览 2 评论 0原文

来加入阵列

a=[];
a=[a,1];

在MATLAB中,您可以通过说:如何与单元格数组进行类似的操作

a={};
a={a,'asd'};

?上面的代码一直在单元格内的嵌套单元格上。我只想将元素附加到单元格数组中。我该如何完成?

In Matlab you can concatenate arrays by saying:

a=[];
a=[a,1];

How do you do something similar with a cell array?

a={};
a={a,'asd'};

The code above keeps on nesting cells within cells. I just want to append elements to the cell array. How do I accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美人如玉 2025-02-07 23:43:55

如果ab是单元格数组,则以相同的方式将它们串联到其他数组:使用[]

>> a={1,'f'}
a =
  1×2 cell array
    {[1]}    {'f'}

>> b={'q',5}
b =
  1×2 cell array
    {'q'}    {[5]}

>> [a,b]
ans =
  1×4 cell array
    {[1]}    {'f'}    {'q'}    {[5]}

您也可以使用功能形式, ,在其中您可以选择要连接的维度:

>> cat(3,a,b)
  1×2×2 cell array
ans(:,:,1) = 
    {[1]}    {'f'}

ans(:,:,2) = 
    {'q'}    {[5]}

要附加单个元素,您可以做a = [a,{1}],但这不是有效的(请参阅 this q& a )。而是do a {end+1} = 1a(end+1)= {1}


请记住,单元格数组就像其他阵列一样。您使用相同的工具来操纵它们,包括索引,您可以使用()进行索引。 ()索引返回与您索引的数组相同类型的数组,因此即使您仅索引一个元素,它也会返回单元格数组。 MATLAB中的几乎每个值都是一个数组,包括6,它是1x1 double数组。

{}语法用于创建单元格数组,并提取其内容:a {1}不是单元格数组,它提取了第一个元素的内容阵列。

{5,8,3}[{5},{8},{3}]相同。 5是双重数组,{5}是包含双数组的单元格数组。

a {5} = 0a(5)= {0}相同。

If a and b are cell arrays, then you concatenate them in the same way you concatenate other arrays: using []:

>> a={1,'f'}
a =
  1×2 cell array
    {[1]}    {'f'}

>> b={'q',5}
b =
  1×2 cell array
    {'q'}    {[5]}

>> [a,b]
ans =
  1×4 cell array
    {[1]}    {'f'}    {'q'}    {[5]}

You can also use the functional form, cat, in which you can select along which dimension you want to concatenate:

>> cat(3,a,b)
  1×2×2 cell array
ans(:,:,1) = 
    {[1]}    {'f'}

ans(:,:,2) = 
    {'q'}    {[5]}

To append a single element, you can do a=[a,{1}], but this is not efficient (see this Q&A). Instead, do a{end+1}=1 or a(end+1)={1}.


Remember that a cell array is just an array, like any other. You use the same tools to manipulate them, including indexing, which you do with (). The () indexing returns the same type of array as the one you index into, so it returns a cell array, even if you index just a single element. Just about every value in MATLAB is an array, including 6, which is a 1x1 double array.

The {} syntax is used to create a cell array, and to extract its content: a{1} is not a cell array, it extracts the contents of the first element of the array.

{5, 8, 3} is the same as [{5}, {8}, {3}]. 5 is a double array, {5} is a cell array containing a double array.

a{5} = 0 is the same as a(5) = {0}.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文