Match cell array of strings to table row names
4 views (last 30 days)
Show older comments
Richard Clarke
on 18 Feb 2019
Answered: Peter Perkins
on 20 Feb 2019
I have a table T1 of unique row names and corresponding weights (size is around 7000 rows)
T1:
row name WEIGHT
raining -1.3
house 3.5
happy 5
etc... (7000 rows)
I have a smaller (~100 row) cell array CA1 of strings, some of which appear in T1, some of which don't. Strings can be repeated in CA1.
CA1:
house
my
feet
raining
raining
etc... (100 rows)
I want all the matches between CA1 and T1 and, for these matches, to return a sum of the weights.
In the example above the output would be: 3.5+0+0-1.3-1.3 = 0.9 (since 'my', and 'feet' don't appear in T1 (hence the zeros) but 'house' and 'raining' do - with 'raining' appearing twice)
I can't make CA1 a table, since the row names wouldn't be unique. If a string appears n times in CA1 i want to have that weight added n times to my final sum.
I've checked the documentation, read a number on answers on this forum, but can't find how to do this. Using strcmp would seem to require an ugly and time consuming loop. I would appreciate any help. Thanks
2 Comments
Accepted Answer
Adam Danz
on 18 Feb 2019
Edited: Adam Danz
on 19 Feb 2019
First I create fake data (in the future, it would be helpful for you to provide this). Then we'll use ismember() to match the row numbers. The variable "weightSum" is the sum of selected weights.
T1 = table([-1.3; 3.5; 5; 1; 2; 3; 4], 'VariableNames', {'Weight'}, 'RowNames', {'raining', 'house', 'happy', 'town', 'city', 'country', 'zip'});
CA1 = {'house'; 'my'; 'feet'; 'raining'; 'raining'; 'mousepad'};
% find rows numbers in T1 that match strings in CA1
[~, rowNum] = ismember(CA1, T1.Properties.RowNames);
% Add the weights of selected rows
rowNum(rowNum==0) = []; %Remove 0s
weightSum = sum(T1.Weight(rowNum))
weightSum =
0.9
2 Comments
More Answers (1)
Peter Perkins
on 20 Feb 2019
Another possibility would be to (simple) join T1 to CA1, and then sum Weight.
0 Comments
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!