Search code examples
stringmatlabcell-array

Find strings of a cell array in another cell array


var_names = {'X1','X2'};
data_pool = {'AB\CD\X1','AB\CD\X1_A','AB\CD\X1_B','AB\CD\X2','AB\CD\X2_A','AB\CD\X2_B'};

The names of the variables I need the data for are X1 and X2. The data pool has variables with similar names; '_A' and '_B' and also the strings have path names so that the strings in data_pool are always longer that those in var_names.

I need to trim down data_pool to the following:

var_names_new = {'AB\CD\X1','AB\CD\X2'};

The full paths for just X1 and X2, not the other postfixed ones.


Solution

  • result = data_pool(endsWith(data_pool, strcat('\', var_names)));
    

    This works as follows:

    1. strcat prepends '\' to each string in var_names;
    2. endsWith produces a logical index of strings in data_pool that end with any of the strings from the previous step;
    3. indexing into data_pool yields the desired result.