Reputation: 95
I know matlab can conveniently get all rows from a table that have the string (in this case) desired_a in the 'a' column like so:
refs_found = refs(strcmp(refs.a,desired_a),:);
However, I want to do this in the case that desired_a is not a string, but a vector with strings, and refs_found to return all rows for which strings in refs.a are also in desired_a.
When I try to do this I unsurprisingly get:
Error using strcmp
Inputs must be the same size or either one can be a scalar.
Is there a way to do this without iterating over each row?
Upvotes: 2
Views: 706
Reputation: 104484
You can use ismember
where you can input in a cell array of strings, and it'll output a logical
vector that tells you which elements in the cell array of strings appears in the source array.
Using an example built into MATLAB, let's create a table:
load patients
refs = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic)
Now let's say I want to find patients whose last names are Jenkins and Griffin. Therefore:
desired_a = {'Griffin', 'Jenkins'};
refs_found = refs(ismember(refs.LastName, desired_a), :);
You would use ismember
to access the rows of the table, with ismember
being called such that the first parameter is the column you are referencing in the table and the second parameter are the strings you want to search for.
We finally get:
>> refs_found = refs(ismember(refs.LastName, desired_a), :)
refs_found =
LastName Gender Age Height Weight Smoker Systolic Diastolic
_________ ______ ___ ______ ______ ______ ________ _________
'Jenkins' 'Male' 28 69 189 true 134 82
'Griffin' 'Male' 49 70 186 false 119 74
In general, first create a cell array of the strings you want to search for:
desired_a = {'string_1', 'string_2', ...};
After, use this to index into your table to get what you need:
refs_found = refs(ismember(refs.a, desired_a), :);
Upvotes: 2