Home > Mobile >  Checking if table contains any element of a specific column in another table
Checking if table contains any element of a specific column in another table

Time:07-15

I want to check if a table column contains any of the elements in another table. Here's the tables:

list1 = ["Hey";"H";"Say"];
list2 = ["Ey";"H";"S"];

Table1 = table(list1);
Table2 = table(list2); 

Now, to check if Table2 contains any of the items in Table1, I wrote this:

for i = 1:3
    if any(strcmp(Table1(:,1),Table2(i,1))) == 1
       disp(Table2(i))
    end
end

The if-statement does not activate for some reason. Might be that the any(strcmp(...)) function does not print out 1 or 0 as I thought it would. It seems that it unputs the entire column and compares it to the one cell in table 2. I thought the "any" function would let the strcmp go through the items. Maybe I have to create a nested for loop to go through the other table for each table 2 items?

CodePudding user response:

Your problem is that Table1(:, 1) and Table(i, 1) returns table and not string arrays.

To be honest I don't know what the behavior of strcmp is in this case and I haven't found any documentation so far.

What you need to do is to transform your table into a string array. For this you have 2 options:

Your code would be somthing like this:

for i = 1:3
    if any(strcmp(Table1(:, 1).Variables, Table2(i, 1).Variables)) == 1
       disp(Table2(i, 1))
    end
end

  • Related