通过索引数组对单元格数组重新排序 [英] Reordering Cell Array by Array of Indices
问题描述
假设我有一个单元格数组x
和一个整数数组y
:
Suppose I have a cell array x
and an integer array y
:
x = {'apple', 'orange', 'banana', 'pear'};
y = [2 4 3 1];
实际上,y
表示x
的索引.我现在想创建一个单元格数组z
,其中x
的元素按这些索引的顺序指定重新排序.这会给我:
In fact, y
represents indices of x
. I want to now create a cell array z
with the elements of x
reordered as specified by the order of these indices. This would give me:
z = {'orange', 'pear', 'banana', 'apple'};
我可以在一行中执行此操作而不必遍历每个元素并将其依次放置在
Can I do this in one line without having to loop through each element and place it in z
in turn?
推荐答案
z = x(y);
由于StackOverflow要求答案的长度至少为30个字符,因此此句子被创建为填充词.
这意味着:将按索引顺序将由索引y
选择的元素为frrm x
的单元格数组放入z
. (这是MATLAB 下标的基础;其他索引方法是 linear 和 logical ,请参见
That means: put in z
the cell array with elements frrm x
, that are selected by the indices y
, in the order of the indices. (that is the basics of MATLAB subscripting; other methods of indexing are linear and logical, see Mathworks site for details).
这篇关于通过索引数组对单元格数组重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!