Search code examples
stringmatlabprefix

How to create a table with all prefix of a string


I have an array of strings: for every string I find prefix and postfix; I take postfix, find prefix and postfix and I repeat this process until the values of the strings finished. I want to create a table with all prefix link among them. Example:

Pfx Pfx2  
'1' '2'                      ---->  1-->2,3
'1' '3' 
'2' ''                       ---->  2-->'',1,3,4
'2' ''
'2' '1'
'2' '1'
'2' '1'
'2' '3'
'2' '3'
'2' '3'
'2' '3'
'2' '4'
'2' '4'
'3' ''                        ---> 3--> '',1,2
'3' ''
'3' ''
'3' ''
'3' '1'
'3' '2'
'3' '2'

At the end, I would obtain a table

Prefix  
  '1'       '2'
            '3'
  '2'       '1'
            '2'
            '3'
  '3'       '1'
            '2'

I have used unique to find the unique values in pfx but I don't know how to link to this values, the values in pfx2: can you give an help?


Solution

  • I think this might do the trick, you should be able to obtain the index from the unique function, and the rest is just grouping and ordering. I am giving my example in the form of loop so you can see what's happening.

    pfx1 = {'1','1','1','1','2','2','2','3','3','3','1'};
    pfx2 = {'','6','9','g','','','17','21','a','b','z'};
     [C ia ic] = unique(pfx1);
    
     for t = 1: size(C,2)
        D{t} =  pfx2(ic == t);
     end
    
     E = vertcat(C,D);
    

    In the end you are left with columns of '1' ,'2' and '3' followed by a cell which consists of all the corresponding pfx2 readings.

    If you want a table, you will need to pad the blank entries with zero or NaN, you should use cell2table which should look something like:

    E = cell2table(D,'VariableNames',C) %remember you need to pad the blank entries first.
    

    Please can someone test/correct this, I am working home today, and only have access to version 2010 which does not have this function.