2.24 Locate rows in a matrix with column being a string

The problem is to select rows in a matrix based on string value in the first column. Then sum the total in the corresponding entries in the second column. Given. For example, given

mat = {'foobar', 77; 
       'faabar', 81; 
       'foobur', 22; 
       'faabaa', 8; 
       'faabian', 88; 
       'foobar', 27; 
       'fiijii', 52};
 

and given list

{'foo', 'faa'}
 

The problem is to select rows in which the string in the list is part of the string in the first column in the matrix, and then sum the total in the second column for each row found. Hence the result of the above should be

    'foo'    'faa' 
    [126]    [ 177]
 

Mathematica

mat = {{"foobar", 77}, 
   {"faabar", 81}, 
   {"foobur", 22}, 
   {"faabaa", 8}, 
   {"faabian", 88}, 
   {"foobar", 27}, 
   {"fiijii", 52}}; 
lst = {"foo", "faa"}; 
 
foo[mat_, lst_] := 
  Select[mat, StringMatchQ[lst, 
      StringTake[#[[1]], 3]] &]; 
 
r = Map[foo[mat, #] &, lst]; 
 
MapThread[{#1, 
 Total[#2[[All, 2]]]}&,{lst, r}]
 

{{"foo", 126}, {"faa", 177}}
 

 

Matlab

A = {'foobar', 77; 
   'faabar', 81; 
   'foobur', 22; 
   'faabaa', 8; 
   'faabian', 88; 
   'foobar', 27; 
   'fiijii', 52}; 
lst= {'foo', 'faa'}; 
f=@(x) [x sum(cell2mat(A(strncmp(A(:,1),x,3),2)))]; 
r=arrayfun(@(i) f(lst(i)),1:2,'UniformOutput',false) 
reshape([r{:}],2,2)
 

ans = 
    'foo'    'faa' 
    [126]    [177]
 

But notice that in Matlab, the answer is a cellarray. To access the numbers above

r{:} 
r{1}{2} 
r{2}{2}
 

ans = 
    'foo'    [126] 
ans = 
    'faa'    [177] 
 
ans = 
   126 
 
ans = 
    177