Matrix - String,Int和组合操作

时间:2016-07-29 08:29:54

标签: python matlab

我希望能够将一个字符串(一个单词)分配给一个整数,并且还能够将整数分配给一个字符串,以便稍后当我对整数或字符串进行排序时,我可以将相应的字符串或整数打印到该字符串矩阵中的单位。 实施例;

103 = QWE
13 = ASD
50 = ZXC
-1 = VBN
253 = RTY

甚至多个职位,如;

105 = QWE
103 = QWE

然后,

matrix = [105,103,13,50,-1,253]
sort = [-1,13,50,103,105,253]

print sort_strings

# output: VBN ASD ZXC QWE QWE RTY

就像在.cvs中一样,当一列对其他列进行排序时,会根据保持行的不变而移动。并希望在文件上做一些额外的功能,比如在输出后对这些字符串进行分类,这样我就可以制作一些带有颜色的图表进行可视化。

由于

2 个答案:

答案 0 :(得分:0)

可以通过MATLAB完成。 我尝试使用矢量化方法。而且每一步都变得越来越不清楚,但我花了很多时间,所以我展示了它:

a1 = ['qve';'rts';'abc';'abc';'def']
a2 = [3;5;10;7;8]
%//find unique strings:
mycell = unique(a1,'rows')

%//find numbers corresponded to each string. 
%//You can see there are 2 numbers correspond to string 'abc'
indexes = arrayfun(@(x) find(all(ismember(a1,mycell(x,:)),2)), 1:size(mycell,1), 'UniformOutput',0)

%//create some descriptive cell array:
mycell2 = arrayfun( @(x) a2(indexes{x}), 1:size(mycell,1),'UniformOutput',0)
mycell = cellstr(mycell)
mycell = [mycell mycell2'] %'

%-------------------------------------------------------------------------
%// now create test array (I use sort like you)
a3 = sort(cell2mat(mycell(:,2)))

%//last step: find each index of a3 in every cell of mycell and put corresponding string to res
res = mycell(arrayfun( @(y) find ( cellfun( @(x) any(ismember(x,y)), mycell(:,2))), a3),1)

a1a2是输入数据。它手动创建。 res是您需要的结果:

res = 

'qve'
'rts'
'abc'
'def'
'abc'

P.S。有用!但它看起来像是一些脑力冲击所以我建议使用循环。

答案 1 :(得分:0)

您正在做的事情被称为“并行排序数组”或“排序并行数组”。您可以使用这些术语来搜索有关如何执行此操作的指南。但是,下面是一些代码,它显示了在MATLAB中实现它的一种方法:

unsorted_keys = [95, 37, 56, 70, 6, 61, 58, 13, 57, 7, 68, 52, 98, 25, 12];

unsorted_strings = cell(size(unsorted_keys));

unsorted_strings = {'crumply', 'going', 'coyotes', 'aficionado', 'bob', 'timeless', 'last', 'bloke', 'brilliant', 'reptile', 'reptile', 'reptile', 'reptile', 'reptile', 'reptile'};

[sorted_keys, indicies] = sort(unsorted_keys);

% indicies = [5, 10, 15, 8, 14, 2, 12, 3, 9, 7  6, 11, 4, 1, 13]

% So, the 5th element of unsorted_keys became the 1st element of sorted_keys
% the 10th element of unsorted_keys became the 2nd element of sorted_keys
% the 15th element of unsorted_keys became the 3rd element of sorted_keys
% the 8th element of unsorted_keys became the 4th element of sorted_keys
% and so on.....
% sorted_keys == unsorted_keys(indicies)

sorted_strings = unsorted_strings(indicies);     
相关问题