Search code examples
stringmatlabsimilaritycell-array

Compare 1 string with a cell array of strings with indexes (Matlab)


I have 1 string and 1 cell array of srings :

  F = 'ABCD'
  R = {'ACBD','CDAB','CABD'};

I would like to compare the string F with all of the strings in R as follows: F(1)='A' and R{1}(1)='A', we will count 1 ( because they have the same value 'A') , F(2)='B' and R{1}(2)='C' we will count 0 ( because they have different values)...and like that until the end of all strings.

We will get same = 2 , dif = 2 for this 'ABCD' and 'ACBD'.

How can I compare F with all the elements in R in the above rule and get the total(same) and total(dif) ?


Solution

  • Assuming all strings in R has the same length as F you can use cellfun:

    same = cellfun( @(r) sum(F==r), R )
    

    Results with

    2     0     1
    

    That is, the same value per string in R. If you want dif:

    dif = numel(F)-same;
    

    If you want the totals:

    tot_same = sum(same);
    tot_dif = sum(dif);