MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   如何在MATLAB中访问嵌套单元格数组? (https://www.labfans.com/bbs/showthread.php?t=23551)

poster 2019-12-10 20:41

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



[B]回答:[/B]

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

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

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

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



[url=https://stackoverflow.com/questions/3086591]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 12:51

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.