Search code examples
stringmatlabcell-array

Delete string element in array (Matlab)


I have a string: pairs = ['AA';'AB';'BB';'AC'; 'CC'; 'CB';'DE'; 'BC']

How can I delete the element which has the same characters in its string like 'AA','BB', 'CC' ?

The expected output should be: out = ['AB';'AC';'CB';'DE';'BC']


Solution

  • Use logical indexing and compare first and second column:

    out = pairs(pairs(:,1)~=pairs(:,2),:)
    

    For a more general way (to cover rows with more than two characters) you can create the index of rows that have all elements equal to each other using bsxfun:

    allsame = any(~bsxfun(@eq, pairs, pairs(:,1)), 2);
    out = pairs(allsame,:);