MATLAB:使用数组元胞数组索引元胞数组并返回元胞数组

发布于 2024-10-23 22:13:47 字数 557 浏览 5 评论 0原文

假设我有一个 (n X 1) 个向量元胞数组 A,以及一个包含 A 索引的向量元胞数组,称为 B 。我希望提取一个元胞数组 C,使得 C{i} = [A{B{i}}]
换句话说,我有一个索引数组元胞数组,并且我想提取与 A 中由每个索引数组索引的向量串联相对应的矩阵。

for i = 1:length(B)
    %# B{i} is an array of indices, C{i} is a matrix
    C{i} = [ A{ B{i} } ];
end

该循环相当于:

C = cellfun(@(x)[A{x}],B,'UniformOutput',false); %# implicit for loop w/ closure

我可以单独使用索引表达式来做到这一点吗?或者至少没有循环?
我认为 deal() 可能必须参与,但无法弄清楚。

Say I have a cell array of (n X 1) vectors, A, and a cell array of vectors containing indices into A, called B. I wish to extract a cell array, C, such that C{i} = [A{B{i}}].
In other words, I have a cell array of arrays of indices, and I want to pull out the matrices corresponding to the concatenations of the vectors in A indexed by each of those arrays of indices.

for i = 1:length(B)
    %# B{i} is an array of indices, C{i} is a matrix
    C{i} = [ A{ B{i} } ];
end

The loop is equivalent to:

C = cellfun(@(x)[A{x}],B,'UniformOutput',false); %# implicit for loop w/ closure

Can I do that using an indexing expression alone? Or at least without the loop?
I think deal() might have to be involved but can't figure it out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

分开我的手 2024-10-30 22:13:47

这里有两种替代解决方案:

  • 收集 B 的所有索引以及函数 cell2mat,索引 A 的内容以形成一个大矩阵,然后使用函数 mat2cell 以及 < 中索引数组的大小代码>B:

    N = 大小(A{1}); % A 中数组的大小
    M = cellfun('prodofsize', B); % B 中元素大小的数组
    C = mat2cell([A{cell2mat(B)}], N, M);
    
  • 这是 < 的更紧凑版本基于 code>cellfun 的解决方案:

    C = cellfun(@(x) {[A{x}]}, B);
    

最终,我会根据速度和可读性来决定使用哪种解决方案,这实际上可能是您基于 for 循环的解决方案。

Here are two alternative solutions:

  • Collect all the indices of B together with the function cell2mat, index the contents of A to make one large matrix, then divide that matrix up using the function mat2cell and the sizes of the index arrays in B:

    N = size(A{1});                        % Size of an array in A
    M = cellfun('prodofsize', B);          % Array of sizes of elements in B
    C = mat2cell([A{cell2mat(B)}], N, M);
    
  • Here's a more compact version of your cellfun-based solution:

    C = cellfun(@(x) {[A{x}]}, B);
    

Ultimately, I would decide what solution to use based on speed and readability, which may actually turn out to be your for-loop-based solution.

笔落惊风雨 2024-10-30 22:13:47

尝试以下表达式:

C = A(cell2mat(B))

您可以查看 Loren 的关于 元胞数组及其内容

Try the following expression:

C = A(cell2mat(B))

You may have a look at Loren's blog post about Cell Arrays and Their Contents

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文