Search code examples
arraysmatlabcells

finding a str in MatLab cells


I am currently using MatLab R2014a

I have one array and one cell:

MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];


MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1};

MyArray consists of code names that are repeatable throughout MyCell. I would like to check if any of the strings in MyArray are in MyCell and if it is, save the name to a new cell.

For now I have:

NewCell = {};
for i = 1:length(MyCell)
    for j = 1:length(MyArray)
        Find = strfind(MyCell(i), MyArray)
        if ~isempty(Find)
            NewCell = {NewCell; MyCell(j)}
        end
    end
end

However, when I use strfind I get this error message:

Undefined function 'strfind' for input arguments of type 'char'

If I use strcmp instead of strfind, I get an array of everything in MyCell repeated by the number of elements in MyArray.

My Ideal output would be:

NewCell1 = {'Name1AA1', 'Name2AA1'}
NewCell2 = {'Name4AB2'}
NewCell3 = {'Name3Acc2'}

ie, no new cell for the code names that are not present in MyArray or no new cell if there is a code name in MyArray but not in MyCell.

Any help is welcome, and thanks for your time


Solution

  • You can use a combination of regular expressions to achieve the desired output. Your approach of wanting to name variables dynamically is not recommended and will lead to code which is harder to debug. Use indexing instead.

    You can read this informative post on Matlab's forum to understand why.

    %Your input data.
    MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];
    MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1'};
    
    %Find common elements between MyArray and MyCell.
    elem = cellfun(@(x) regexp(MyArray,x(end-2:end),'match'),MyCell,'un',0);
    
    %Eliminate duplicates.
    NewCell = unique([elem{:}]);
    
    %Find elements in MyCell which end with NewCell elements and group them.
    NewCell = cellfun(@(x) regexp([MyCell{:}],strcat('Name\d\w?',x),'match'),NewCell,'un',0);
    
    %Join elements. 
    NewCell{1} = {strjoin(NewCell{1},''',''')};
    

    NewCell{1} = {'Name1AA1','Name2AA1'}

    NewCell{2} = {'Name4AB2'}

    NewCell{3} = {'Name3Acc2'}