Recognize relevant string information by checking the first characters

大憨熊 提交于 2019-12-25 11:48:14

问题


I have a table with 2 columns. In column 1, I have a string information, in column 2, I have a logical index

%% 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

UPDATES:

  • I will update this section as soon as I know how to copy my workspace into a code format

** still don't know how to do that but here it goes

*** why working with tables is a double edged sword (but still cool): I have to be very aware of the class inside the table to refer to it in an if else construct, here I had to convert two columns to categorical and to double from cell to make it work...

Here is what my data looks like:

I want to have this:

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

I manage to tell matlab to do as i wish, but the whole point of this post is: how do i tell matlab to ignore what comes after A2P3 in the string, where the string length is variable? because otherwise it would be very tiring to look up every single piece of string information left on A2P3 (and on B2P3 etc) just to say thay.

How do I do that?


回答1:


Assuming you are working with T (cell array) as listed in your code, you may use this code to detect the successful matches -

%%// 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))



回答2:


One quick solution would be to make a function that takes 2 strings and checks whether the first one starts with the second one.

Later Edit:

The function will look like this:

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

This assuming the second character's lenght is always smaller the first's. Otherwise, return the function with the arguments swapped.



来源:https://stackoverflow.com/questions/23195091/recognize-relevant-string-information-by-checking-the-first-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!