MATLAB: How to use regexp in a more complex example

cell arrayindicesregexp

This MATLAB code returns an array called "selected motors" at line 23 via user entry.
I would like to get all the indices(row number) of cells in raw2 1st column that have the string 1-2-3 and the selected motors values in them.

Best Answer

In two regexp calls:
>> selected_motor = [1111,4444];
>> C = {'1111 1-2-3';'2222 1-2-3';'3333 4-5-6';'4444 7-8-9';'4444 1-2-3'}
C =
'1111 1-2-3'
'2222 1-2-3'
'3333 4-5-6'
'4444 7-8-9'
'4444 1-2-3'
>> tmp = sprintf('|%d',selected_motor);
>> idx = ~cellfun('isempty',regexp(C,'1-2-3$','once'));
>> idy = ~cellfun('isempty',regexp(C,sprintf('^(%s)',tmp(2:end)),'once'));
>> C(idx & idy)
ans =
'1111 1-2-3'
'4444 1-2-3'
or one regexp call:
>> idz = ~cellfun('isempty',regexp(C,sprintf('^(%s) 1-2-3$',tmp(2:end)),'once'));
>> C(idz)
ans =
'1111 1-2-3'
'4444 1-2-3'
If you wish to experiment with regular expressions, then you can use my FEX submission Regular Expression Helper to create and change regular expressions in real time, and see the outputs in real time: