MATLAB:使用数组元胞数组索引元胞数组并返回元胞数组
假设我有一个 (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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有两种替代解决方案:
收集
B
的所有索引以及函数cell2mat
,索引A
的内容以形成一个大矩阵,然后使用函数mat2cell
以及 < 中索引数组的大小代码>B:这是 < 的更紧凑版本基于 code>cellfun 的解决方案:
最终,我会根据速度和可读性来决定使用哪种解决方案,这实际上可能是您基于 for 循环的解决方案。
Here are two alternative solutions:
Collect all the indices of
B
together with the functioncell2mat
, index the contents ofA
to make one large matrix, then divide that matrix up using the functionmat2cell
and the sizes of the index arrays inB
:Here's a more compact version of your
cellfun
-based solution: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.
尝试以下表达式:
您可以查看 Loren 的关于 元胞数组及其内容
Try the following expression:
You may have a look at Loren's blog post about Cell Arrays and Their Contents