在Matlab中,我可以访问数组的元素,而元素又是container.Map的值吗?

Ant*_*yko 5 arrays matlab containers types map

这是一个代码片段,它显示了我想要的内容和错误,如下所示:

a = [1, 2];
m = containers.Map('KeyType','char', 'ValueType','any');
m('stackoverflow.com') = a;
pull_the_first_element_of_the_stored_array = m('stackoverflow.com')(1);
??? Error: ()-indexing must appear last in an index expression.
Run Code Online (Sandbox Code Playgroud)

如何访问数组的元素,而元素又是地图对象的值?我本可以这样做的:

temp = m('stackoverflow.com');
pull_the_first_element_of_the_stored_array = temp(1);
Run Code Online (Sandbox Code Playgroud)

但我不想创建一个中间数组只是为了从中拉出一个值.

编辑:这是一个副本如何索引函数返回的MATLAB数组,而不首先将其分配给局部变量?答案就在那里.

Pur*_*uit 6

这是另一种情况,您可以通过小辅助函数来解决语法限制.例如:

getFirst = @(x)x(1);

pull_the_first_element_of_the_stored_array = getFirst(m('stackoverflow.com'));
Run Code Online (Sandbox Code Playgroud)

这仍然需要两行,但您通常可以重用函数定义.更一般地说,你可以写:

getNth = @(x, n) x(n);
Run Code Online (Sandbox Code Playgroud)

然后使用:

getNth (m('stackoverflow.com'),1);
Run Code Online (Sandbox Code Playgroud)


gno*_*ice 1

虽然这个问题与上一个问题重复,但我觉得有必要指出他们正在解决的问题之间的一个小差异,以及如何稍微调整我之前的答案......

上一个问题涉及如何解决在同一行上紧接着进行索引操作的函数调用所涉及的语法问题。相反,这个问题涉及同一行上紧接着的两个索引操作。我的其他答案中的两个解决方案(使用SUBSREF或辅助函数)也适用,但实际上有一种使用 SUBSREF 的替代方法,它结合了两个索引操作,如下所示:

value = subsref(m,struct('type','()','subs',{'stackoverflow.com',{1}}));
Run Code Online (Sandbox Code Playgroud)

请注意顺序索引下标'stackoverflow.com'1是如何组合到元胞数组中以创建 1×2结构体数组以传递给 SUBSREF 的。它仍然是一个丑陋的单行,为了可读性,我仍然主张使用临时变量解决方案。