登录论坛

查看完整版本 : 如何在MATLAB中访问嵌套单元格数组?


poster
2019-12-10, 20:41
我想制作一个嵌套的单元格数组,如下所示:

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的内置类不起作用,我可以编写自己的类来执行此操作,但是有解决这个问题的简单技巧吗?



回答:

x(1)的返回值实际上是一个1比1单元格数组,其中包含另一个 1比1单元格数组,该数组本身包含字符串'slot1' 。要访问单元格数组(而不只是单元格的子数组)的内容 ,您必须使用花括号(即“ content indexing” (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-98.html#br04bw6-108) )而不是括号(即“ cell indexing” (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-98.html#br04bw6-108) )。

例如,如果要从x检索字符串'slot1'以进行字符串比较,则可以通过以下两种方式之一进行:

cstr = x{1}; %# Will return a 1-by-1 cell array containing 'slot1' str = x{1}{1}; %# Will return the string 'slot1' 然后,您可以将STRCMP (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/strcmp.html)函数与以上任一功能结合使用:

isTheSame = strcmp(cstr,'slot1'); %# Returns true isTheSame = strcmp(str,'slot1'); %# Also returns true 上面的方法之所以有效,是因为在许多内置函数中,MATLAB中的字符串单元格数组 (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f2-47856.html#f2-38312)可以与字符串和字符数组互换一些使用。



更多&回答... (https://stackoverflow.com/questions/3086591)