单元阵列的排名 [英] Ranking of a cell array
问题描述
以下面的示例为例:
clear all
Name1 = {'Data1','Data2','Data3','Data4'};
Data = {6.2,6,3.2,8};
CombnsName = nchoosek(Name1,2);
CombnsData = nchoosek(Data,2);
for i = 1:length(CombnsData);
multiplied{i} = CombnsData{i,1}.*CombnsData{i,2};
end
multiplied = multiplied';
Final = [CombnsName, multiplied];
Rankd = sort(cell2mat(multiplied));
在此,Final表示通过将"Name1"的每种可能组合相乘而获得的值.现在,我试图找到一种方法来更改最终"的顺序以与"Rankd"定义的排名顺序相对应.例如,Final的第一行应为"Data2'Data3'19.2;最后一个行"应显示为"Data1","Data4" 49.6.
Here, Final represents the values gained by multiplying every possible combination of 'Name1'. Now, I'm trying to find a way of changing the order of 'Final' to correspond to the ranking order defined by 'Rankd'. For example the first 'line' of Final should read 'Data2 'Data3' 19.2; and the last 'line' should read 'Data1' Data4' 49.6.
有没有这样做的方法?
推荐答案
有两个选项.首先,您可以使用sort
的第二个输出,它为您提供与已排序数组中的条目相对应的索引:
There are a couple of options. Firstly, you could use the second output of sort
, which gives you the indexes corresponding to the entries in the sorted array:
>> [Rankd Index] = sort(cell2mat(multiplied));
然后做
>> Final(Index,:)
ans =
'Data2' 'Data3' [19.200000000000003]
'Data1' 'Data3' [19.840000000000003]
'Data3' 'Data4' [25.600000000000001]
'Data1' 'Data2' [37.200000000000003]
'Data2' 'Data4' [ 48]
'Data1' 'Data4' [49.600000000000001]
但是,更简单的方法是使用专门针对这种情况设计的功能sortrows
:
However, an even easier method is to use the function sortrows
which was designed for exactly this situation:
>> sortrows(Final,3)
ans =
'Data2' 'Data3' [19.200000000000003]
'Data1' 'Data3' [19.840000000000003]
'Data3' 'Data4' [25.600000000000001]
'Data1' 'Data2' [37.200000000000003]
'Data2' 'Data4' [ 48]
'Data1' 'Data4' [49.600000000000001]
这篇关于单元阵列的排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!