MATLAB查找字符串,存储在数组中并连接

时间:2017-06-13 13:53:58

标签: arrays matlab find concatenation

我有一个6x2的单元格数组如下:

import sys

def dprint(fmt=None, *args, **kwargs):
    try:
        name = sys._getframe(1).f_code.co_name
    except (IndexError, TypeError, AttributeError):  # something went wrong
        name = "<unknown>"
    print("[{}] {}".format(name, (fmt or "{}").format(*args, **kwargs)))

def testfunction1():
    dprint("Running {}", 1)

def testfunction2():
    dprint("Running {}", 2)

def main():
    dprint("Running {}", 0)
    testfunction1()
    testfunction2()
    return 0

if __name__ == "__main__":
    main()

# prints:
# [main] Running 0
# [testfunction1] Running 1
# [testfunction2] Running 2

我想要做的是找到所有相应的单词并自动连接它们。例如,我想找到所有的Word1并连接它们,以便MSW从左侧开始,如:'12345678'。然后我想将它们存储到一个新的数组中,以便我有:

'Word1_MSW' '1234'
'Word1_LSW' '5678'
'Word2_MSW' '1234'
'Word2_LSW' '5678'
'Word3_MSW' '1234'
'Word3_LSW' '5678'

2 个答案:

答案 0 :(得分:4)

对于此解决方案,我们首先使用strtok'_'的第1列中打破字符串,并将第二个字符串放在C的第三列中:

[C(:, 1), C(:, 3)] = strtok(C(:, 1), '_');

接下来,使用sortrows按第一列(升序)和第三列(降序)排序C行,并使用{{3}在第一列中查找唯一的字符串和索引}}:

C = sortrows(C, [1 -3]);
[uniqueWords, ~, index] = unique(C(:, 1));

最后,使用uniquemat2cell对第二列中的值进行分组,使用accumarray水平连接每个组中的字符串,并创建一个包含唯一字符串的新单元格数组:

wordGroups = mat2cell(C(:, 2), accumarray(index, 1));
out = [uniqueWords cellfun(@(c) {[c{:}]}, wordGroups)];

您的样本C的结果:

out =

  3×2 cell array

    'Word1'    '12345678'
    'Word2'    '12345678'
    'Word3'    '12345678'

答案 1 :(得分:0)

以下内容可能有效,或者至少可能有所帮助:

numOfWords = 3;     % Enter number of separate 'Words'

for i=1:numOfWords
    wordNum = num2str(i);
    testWord_MSW = ['Word' wordNum '_MSW'];     % Create words to match
    testWord_LSW = ['Word' wordNum '_LSW']; 
    matchingCell_MSW = strmatch(testWord_MSW,cellArray{1}(1:end,:));    % Find matching words
    matchingCell_LSW = strmatch(testWord_LSW,cellArray{1}(1:end,:));
    concatWord = [cellArray{2}(matchingCell_MSW,:) cellArray{2}(matchingCell_LSW,:)];   % Concatenate MSW and LSW words
    finalArray{1}(i,:) = ['Word' wordNum];
    finalArray{2}(i,:) = concatWord;
end