【问题标题】:Matrix - String, Int, and Combined Operations矩阵 - 字符串、整数和组合操作
【发布时间】:2016-12-03 21:24:06
【问题描述】:

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

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

谢谢

【问题讨论】:

标签: python matlab


【解决方案1】:

可以通过 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'

附:有用!但这看起来有点脑筋急转弯,所以我建议使用循环。

【讨论】:

    【解决方案2】:

    您所做的称为“并行排序数组”或“排序并行数组”。您可以使用这些术语来搜索有关如何操作的指南。但是,下面是一些代码,显示了在 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);     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 2013-11-16
      • 2020-09-08
      • 1970-01-01
      • 2017-12-05
      • 2021-12-29
      • 1970-01-01
      相关资源
      最近更新 更多