如何在 MATLAB 中访问嵌套元胞数组?
我想制作一个嵌套元胞数组,如下所示:
tag = {'slot1'}
info = {' name' 'number' 'IDnum'}
x = {tag , info}
并且我希望能够调用 x(tag(1))
并让它显示 'slot1'
。相反,我收到此错误:
??? Error using ==> subsindex
Function 'subsindex' is not defined for values of class 'cell'.
如果我调用 x(1)
,MATLAB 将显示 {1x1 cell}
。我希望能够访问列表 x
中的第一个单元格,以便我可以与另一个字符串进行字符串比较。
我知道如果 MATLAB 的内置类不起作用,我可以编写自己的类来执行此操作,但是有一个简单的技巧可以解决这个问题吗?
I would like to make a nested cell array as follows:
tag = {'slot1'}
info = {' name' 'number' 'IDnum'}
x = {tag , info}
And I want to be able to call x(tag(1))
and have it display 'slot1'
. Instead I am getting this error:
??? Error using ==> subsindex
Function 'subsindex' is not defined for values of class 'cell'.
If I call x(1)
MATLAB displays {1x1 cell}
. I want to be able to access the first cell in the list x
so I can do a string comparison with another string.
I know I can write my own class to do this if MATLAB's built in class does not work but is there a simple trick to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
x(1)
的返回值实际上是一个 1×1 元胞数组,其中包含另一个 1×1 元胞数组,该数组本身包含字符串'插槽1'
。要访问元胞数组的内容(而不仅仅是元胞的子数组),您必须使用大括号(即"内容索引")而不是括号(即 "单元格索引")。例如,如果您想从
x
检索字符串'slot1'
以便进行字符串比较,您可以通过以下两种方式之一来完成:然后您可以将函数 STRCMP 与上述任意一项一起使用
:上面的工作原理是因为 字符串单元格数组 在许多内置函数中与字符串和字符数组在某种程度上可以互换处理。
The return value of
x(1)
is actually a 1-by-1 cell array containing another 1-by-1 cell array which itself contains the string'slot1'
. To access the contents of cell arrays (and not just a subarray of cells) you have to use curly braces (i.e. "content indexing") instead of parentheses (i.e. "cell indexing").For example, if you want to retrieve the string
'slot1'
fromx
in order to do a string comparison, you could do it in one of two ways:Then you can use the function STRCMP with either of the above:
The above works because cell arrays of strings in MATLAB are handled somewhat interchangeably with strings and character arrays in many built-in functions.
您可以使用结构而不是使用元胞数组:
然后,您将获得第一个标记:
或者,您可以使用标记名称作为字段名称。如果标签名称和信息是元胞数组,则可以传递元胞数组而不是“slot1”和“信息此处”,并且一次性创建了结构。
Instead of using a cell array, you could use a structure:
Then, you get the first tag as
Alternatively, you could use tag names as fieldnames. If tag names and information are cell arrays, you can pass the cell arrays instead of 'slot1' and 'information here', and you have the structure created in one go.