'MATLAB: Subindexing in cell array based on results of strfind

I have a cell array, like so:

ID = {'g283', 'sah378', '2938349dgdgf', 'g283'};

I also have some data that corresponds to these IDs.

Data = {'data1', 'data2', 'data3', 'data4'};

Let's say my current ID is g283, and I want to extract Data that matches this ID.

I do strfind(ID, 'g283') and get a result like so:

result = {[1], [], [], [1]}

I now want to extract the data from data and get this:

new_data = ['data1', 'datat4'] or equivalent.

However, cell arrays cannot be subindexed into, so I am wondering if there is an easy method to do this without looping. Thank you!



Solution 1:[1]

Let the input variables be defined as

ID = {'g283', 'sah378', '2938349dgdgf', 'g283'}; % ID
Data = {'data1', 'data2', 'data3', 'data4'}; % data
s = 'g283'; % current ID

You only need to apply isempty to test if each result of strfind contains a match or not. This can be done via cellfun, for example as follows:

ind = cellfun(@(x) ~isempty(strfind(x, s)), ID);
new_data = Data(ind);

If you are looking for the whole string (as opposed to a partial match), a simpler alternative is to use ismember:

ind = ismember(ID, s);
new_data = Data(ind);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1