0

我有一个有 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 等)上的每一条字符串信息只是为了说 thay 会非常累人。

我怎么做?

4

2 回答 2

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))
于 2014-04-22T08:06:40.710 回答
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

假设第二个字符的长度总是小于第一个字符。否则,返回交换了参数的函数。

于 2014-04-21T10:07:52.453 回答