I have a function that uses strfind
in a cellfun
call to find which string items in a cell array match a specified string. For example:
cellfun( @(x) strfind( x , 'openmask'), fileNames, 'uniformoutput', false)
The original cell matrix is like this:
fileNames = {'sub11att-openmask.txt', 'sub13det-masking', ...};
The result for this looks like this:
[10] [] [10] [] [9] []
I am trying to find a function that will convert this to:
10 0 10 0 9 0
Using cell2mat
I get:
10 10 9
So I have to use this currently:
x(cellfun('isempty', x))={0};
cell2mat(x);
Is there a function that is cleaner than this (i.e. a one-liner solution)?
Thanks.
This works even if there are several occurrences of the sought string. It finds the first such occurrence if there's any, or gives 0
otherwise:
result = cellfun(@(x) sum(min(strfind(x, 'openmask'))), fileNames);
The code uses min
to keep the first occurrence. This will give either a number or []
. Then sum
transforms []
into 0
.
If you prefer to keep the last occurrence, change min
to max
or use Sardar Usama's suggestion:
result = cellfun(@(x) max([0 strfind(x, 'openmask')]), fileNames);