通过检查第一个字符来识别相关的字符串信息

时间:2014-04-21 10:02:03

标签: string matlab identify

我有一个包含2列的表格。在第1列中,我有一个字符串信息,在第2列中,我有一个逻辑索引

%% Tables and their use

T={'A2P3';'A2P3';'A2P3';'A2P3 with (extra1)';'A2P3 with (extra1) and (extra 2)';'A2P3 with (extra1)';'B2P3';'B2P3';'B2P3';'B2P3 with (extra 1)';'A2P3'};
a={1 1 0 1 1 0 1 1 0 1 1 }

T(:,2)=num2cell(1);
T(3,2)=num2cell(0);
T(6,2)=num2cell(0);
T(9,2)=num2cell(0);

T=table(T(:,1),T(:,2));

class(T.Var1);
class(T.Var2);

T.Var1=categorical(T.Var1)
T.Var2=cell2mat(T.Var2)

class(T.Var1);
class(T.Var2);

if T.Var1=='A2P3' & T.Var2==1
    disp 'go on'
else
    disp 'change something'
end

更新:

  • 我知道如何将工作区复制为代码格式后,我会立即更新此部分

**仍然不知道该怎么做但在这里

***为什么使用表是一把双刃剑(但仍然很酷):我必须非常了解表中的类,在if else构造中引用它,这里我必须转换两列分类和加倍从单元格,使其工作...

以下是我的数据:

http://imgur.com/H2exXKO

我想要这个:

if T.Var1=='A2P3*************************' & T.Var2==1
    disp 'go on'
else
    disp 'change something'
end

我设法告诉matlab按照我的意愿去做,但这篇文章的重点是:我如何告诉matlab忽略字符串中A2P3之后的内容,其中字符串长度是可变的?因为否则,查看A2P3(和B2P3等)上留下的每一条字符串信息都会非常累人。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

假设您正在使用代码中列出的T(单元格数组),您可以使用此代码来检测成功匹配 -

%%// Slightly different than yours
T={'A2P3';'NotA2P3';'A2P3';'A2P3 with (extra1)';'A2P3 with (extra1) and (extra 2)';'A2P3 with (extra1)';'B2P3';'B2P3';'NotA2P3';'B2P3 with (extra 1)';'A2P3'};
a={1 1 0 1 1 0 1 1 0 1 1 }

T(:,2)=num2cell(1);
T(3,2)=num2cell(0);
T(6,2)=num2cell(0);
T(9,2)=num2cell(0);

%%// Get the comparison results
col1_comps = ismember(char(T(:,1)),'A2P3') | ismember(char(T(:,1)),'B2P3');
comparisons = ismember(col1_comps(:,1:4),[1 1 1 1],'rows').*cell2mat(T(:,2))

答案 1 :(得分:0)

一个快速的解决方案是创建一个带2个字符串的函数,并检查第一个字符串是否以第二个字符串开头。

稍后编辑:

该功能如下所示:

for i = 0, i < second string's length, i = i + 1
    if the first string's character at index i doesn't equal the second string's character at index i
        return false
after the for, return true

这假设第二个角色的长度总是小于第一个角色。否则,返回带有参数swapped的函数。