2016-07-29 21 views
0

我想能够分配一个字符串(一个字)到一个整数,也是一个整数字符串,以便稍后当我排序整数或字符串,我可以在矩阵中打印相应的字符串或整数。 示例;矩阵 - 字符串,内联和组合操作

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,当列排序其他列举动根据保持完好行。并希望在文件上做一些额外的功能,比如输出后对这些字符串进行分类,以便我可以制作一些带有颜色的图表以便进行可视化。

谢谢

+3

您的标记是Python和Matlab。你使用哪种语言? –

+3

Python字典可能在此处有用,因为您无法真正将整数声明为变量并将其分配给它。 – BusyAnt

+0

使用Matlab,您可以创建一个单元格矢量并将每个字符串分配给它的相应位置。 A {103} ='QWE';一个{13} ='13'等等......虽然如果大多数职位都是空的,它可能是低效率的。 –

回答

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.有用!但它看起来像一些brainblow,所以我建议使用循环。

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);