比较名称字符串

时间:2014-07-07 16:34:54

标签: string matlab

我正在尝试比较两个字符串的名称,并尝试选择未包含在另一个字符串中的名称。

h = 1;
for i = 1:name_size_main
    checker = 0;
    main_name = main(i);
    for j = 1:name_size_image
        image_name = image(j);
        temp = strcmpi(image_name, main_name);
        if temp == 1;
            checker = temp;
        end
    end
    if checker == 0
        result(h) = main_name;
        h = h+1;
    end
end

但它不断返回整个字符串,主字符串包含大约1000个名称,图像名称包含大约300个名称,因此它应返回大约700个名称,但它会返回所有1000个名称。

2 个答案:

答案 0 :(得分:1)

我用小向量尝试了你的代码:

main = ['aaa' 'bbb' 'ccc' 'ddd'];
image = ['bbb' 'ddd'];
name_size_main = size(main,2);
name_size_image = size(image,2);

h = 1;
for i = 1:name_size_main
    checker = 0;
    main_name = main(i);
    for j = 1:name_size_image
        image_name = image(j);
        temp = strcmpi(image_name, main_name);
        if temp == 1;
            checker = temp;
        end
    end
    if checker == 0
        result(h) = main_name;
        h = h+1;
    end
end

我得到result = 'aaaccc',这不是你想得到的吗?

编辑:

如果您使用的是单元格数组,则应将行result(h) = main_name;更改为result{h} = main_name;,如下所示:

main = {'aaa' 'bbb' 'ccc' 'ddd'};
image = {'bbb' 'ddd'};
name_size_main = size(main,2);
name_size_image = size(image,2);
result = cell(0);
h = 1;
for i = 1:name_size_main
    checker = 0;
    main_name = main(i);
    for j = 1:name_size_image
        image_name = image(j);
        temp = strcmpi(image_name, main_name);
        if temp == 1;
            checker = temp;
        end
    end
    if checker == 0
        result{h} = main_name;
        h = h+1;
    end
end

答案 1 :(得分:0)

您可以将字符串单元格与setdiffsetxor一起使用。

    A = cellstr(('a':'t')')  % a cell of string, 'a' to 't'
    B = cellstr(('f':'z')')  % 'f' to 'z'

    C1 = setdiff(A,B,'rows') % gives 'a' to 'e'
    C2 = setdiff(B,A,'rows') % gives 'u' to 'z'
    C3 = setxor(A,B,'rows')  % gives 'a' to 'e' and 'u' to 'z'