matlab:结构数据和多级索引

时间:2022-10-06 04:16:06

I have a simple problem with structures.

我有一个简单的结构问题。

Lets create:

x(1).a(:, :) = magic(2);
x(2).a(:, :) = magic(2)*2;
x(3).a(:, :) = magic(2)*3;

how to list a(1, 1) from all x-es?

如何列出所有x-es中的(1,1)?

i wanted to do it like:

我想这样做:

x(1, :).a(1,1)

but there is an error "Scalar index required for this type of multi-level indexing."

但是有一个错误“这种类型的多级索引需要标量索引。”

How to approach it? I know I can do it with a loop, but that's probably the worst solution :) Thanks!

如何接近它?我知道我可以用循环来做,但这可能是最糟糕的解决方案:)谢谢!

2 个解决方案

#1


2  

This is not the best datastructure to use if this is the sort of query you'd like to make on it, precisely because this sort of indexing cannot be done directly.

如果这是您要对其进行的那种查询,这不是最好的数据结构,正是因为这种索引不能直接完成。

However, here is one approach that works:

但是,这是一种有效的方法:

cellfun(@(X) X(1,1), {x.a})

The syntax {x.a} converts x from a 'struct array' into a cell array. Then we use cellfun to apply a function as a map over the cell array. The anonymous function @(X) X(1,1) takes one argument X and returns X(1,1).

语法{x.a}将x从'struct array'转换为单元数组。然后我们使用cellfun将函数应用为单元格数组上的映射。匿名函数@(X)X(1,1)接受一个参数X并返回X(1,1)。

#2


2  

You can also get your data in this way:

您也可以这样获取数据:

B = cat(3,x.a);
out = reshape(B(1,1,:),1,[]);

By the way, loops are not evil. Sometimes they are even faster than vectorized indexation. Try it both ways, see what suits you best in terms of:

顺便说一句,循环不是邪恶的。有时它们甚至比矢量化索引更快。尝试两种方式,看看最适合你的方面:

  • Speed - use the profiler to check
  • 速度 - 使用分析器进行检查

  • Code clarity - depends on the context. Sometimes vectorized code looks better, sometimes the opposite.
  • 代码清晰度 - 取决于上下文。有时矢量化代码看起来更好,有时相反。

#1


2  

This is not the best datastructure to use if this is the sort of query you'd like to make on it, precisely because this sort of indexing cannot be done directly.

如果这是您要对其进行的那种查询,这不是最好的数据结构,正是因为这种索引不能直接完成。

However, here is one approach that works:

但是,这是一种有效的方法:

cellfun(@(X) X(1,1), {x.a})

The syntax {x.a} converts x from a 'struct array' into a cell array. Then we use cellfun to apply a function as a map over the cell array. The anonymous function @(X) X(1,1) takes one argument X and returns X(1,1).

语法{x.a}将x从'struct array'转换为单元数组。然后我们使用cellfun将函数应用为单元格数组上的映射。匿名函数@(X)X(1,1)接受一个参数X并返回X(1,1)。

#2


2  

You can also get your data in this way:

您也可以这样获取数据:

B = cat(3,x.a);
out = reshape(B(1,1,:),1,[]);

By the way, loops are not evil. Sometimes they are even faster than vectorized indexation. Try it both ways, see what suits you best in terms of:

顺便说一句,循环不是邪恶的。有时它们甚至比矢量化索引更快。尝试两种方式,看看最适合你的方面:

  • Speed - use the profiler to check
  • 速度 - 使用分析器进行检查

  • Code clarity - depends on the context. Sometimes vectorized code looks better, sometimes the opposite.
  • 代码清晰度 - 取决于上下文。有时矢量化代码看起来更好,有时相反。