如何在MATLAB中访问嵌套单元数组?
我想制作一个嵌套单元格数组,如下所示:如何在MATLAB中访问嵌套单元数组?,matlab,nested,cell-array,Matlab,Nested,Cell Array,我想制作一个嵌套单元格数组,如下所示: tag = {'slot1'} info = {' name' 'number' 'IDnum'} x = {tag , info} 我希望能够调用x(标记(1))并让它显示'slot1'。相反,我得到了以下错误: ??? Error using ==> subsindex Function 'subsindex' is not defined for values of class 'cell'. 如果我调用x(1)MATLAB显示{1x1单元
tag = {'slot1'}
info = {' name' 'number' 'IDnum'}
x = {tag , info}
我希望能够调用x(标记(1))
并让它显示'slot1'
。相反,我得到了以下错误:
??? Error using ==> subsindex
Function 'subsindex' is not defined for values of class 'cell'.
如果我调用x(1)
MATLAB显示{1x1单元格}
。我希望能够访问列表中的第一个单元格x
,以便与另一个字符串进行字符串比较
我知道如果MATLAB的内置类不起作用,我可以编写自己的类来实现这一点,但是有没有简单的技巧来解决这个问题?x(1)的返回值实际上是一个1乘1单元数组,其中包含另一个1乘1单元数组,该数组本身包含字符串
'slot1'
。要访问单元格数组(而不仅仅是单元格的子数组)的内容,必须使用大括号(即)而不是圆括号(即)
例如,如果要从x
中检索字符串'slot1'
,以便进行字符串比较,可以采用以下两种方法之一:
cstr = x{1}; %# Will return a 1-by-1 cell array containing 'slot1'
str = x{1}{1}; %# Will return the string 'slot1'
然后,您可以将该功能与上述任一功能一起使用:
isTheSame = strcmp(cstr,'slot1'); %# Returns true
isTheSame = strcmp(str,'slot1'); %# Also returns true
上述方法之所以有效,是因为在MATLAB中,在许多内置函数中,字符串和字符数组在某种程度上可以互换处理。您可以使用以下结构,而不是使用单元格数组:
x(1) = struct('tag','slot1','info',{{'something'}}); %# using '1' in case there are many
然后,您将获得第一个标记作为
x(1).tag
或者,您可以使用标记名作为字段名。如果标记名和信息是单元格数组,则可以传递单元格数组,而不是“slot1”和“information here”,这样就可以一次性创建结构
x = struct('slot1','information here')
tagName = 'slot1';
%# access the information via tag names
x.(tagName)
我也遇到过同样的问题,但原因是我使用的函数名(错误地)与另一个函数中已知的单元名相同。错误是让我们学习的。我只是想和大家分享一下