【问题标题】:In Matlab, can I access an element of an array, which is in turn a value of a container.Map?在 Matlab 中,我可以访问数组的元素,它又是 container.Map 的值吗?
【发布时间】:2012-03-11 00:08:56
【问题描述】:

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

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.

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

temp = m('stackoverflow.com');
pull_the_first_element_of_the_stored_array = temp(1);

但我不想创建一个中间数组只是为了从中提取一个值。

编辑:这是How can I index a MATLAB array returned by a function without first assigning it to a local variable?的副本,答案就在那里。

【问题讨论】:

标签: arrays matlab types map containers


【解决方案1】:

这是另一种情况,您可以使用小型辅助函数绕过语法限制。例如:

getFirst = @(x)x(1);

pull_the_first_element_of_the_stored_array = getFirst(m('stackoverflow.com'));

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

getNth = @(x, n) x(n);

然后使用:

getNth (m('stackoverflow.com'),1);

【讨论】:

    【解决方案2】:

    虽然这个问题与this previous question 重复,但我觉得有必要指出他们正在解决的问题之间的一个小区别,以及如何稍微调整my previous answer...

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

    value = subsref(m,struct('type','()','subs',{'stackoverflow.com',{1}}));
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多