Search code examples
stringmatlabcell-array

Find strings from an cell array and create a new cell array


I want to find the strings from an cell array (m x n) and add those identified strings in new cell array (m x n), by using matlab, for example:

Human(i,1)={0
1
34
eyes_two
55
33
ears_two
nose_one
mouth_one
631
49
Tounge_one}

I want to remove the numbers and have just strings

New_Human(i,1)={eyes_two
ears_two
nose_one
mouth_one
tounge_one}

Solution

  • Based on your comment it sounds like all your data is being stored as strings. In that case you can use the following method to remove all strings which represent a valid number.

    H = {'0'; '1'; '34'; 'eyes_two'; '55'; '33'; 'ears_two'; 'nose_one'; 'mouth_one'; '631'; '49'; 'Tounge_one'};
    
    idx = cellfun(@(x)isnan(str2double(x)), H);
    Hstr = H(idx)
    

    Output

    Hstr = 
        'eyes_two'
        'ears_two'
        'nose_one'
        'mouth_one'
        'Tounge_one'
    

    The code determines which strings do not represent valid numeric values. This is accomplished by checking if the str2double function returns a NaN result on each string. If you want to understand more about how this works I suggest you read the documentation on cellfun.