I'm having trouble indexing into strings contained in a cell array using the cellfun function. I have a cell array with strings of various contents, and I'm trying to extract the numbers between the words "input" and "dBm" in the following example, where the lines of interest always have the word "atten". (My actual usage has dozens of lines, but this is a simplified example). I'm able to get the indices for the cells that contain "atten" using the "contains" function, which works as expected. I am also able to get the indices in each cell that I want to extract using the "strfind" function inside cellfun, which are showed as variables "st" and "sp" below.
But I'm unable to use the "st" and "sp" values to extract the numbers of interest, which are -70.6, -67.5, and -69.9 in this example. Is this type of indexing possible using cellfun? Or should I just go with a for loop?
The commented code at the bottom shows the values I'm getting in out_cell_array currently, and what I what to obtain.
d = {'some random text';...
'atten 16.0 input -70.6 dBm';...
'atten 0.0 input -67.5 dBm';...
'atten 13.0 input -69.9 dBm';...
'some other random text'};
idx = find(contains(d,'atten'));
st = cellfun(@(x) strfind(x, 'input'), d(idx)) + 6; % index starting 6 to the right "input"
sp = cellfun(@(x) strfind(x, 'dBm'), d(idx)) - 2; % index starting 2 to the left of "dBm"
out_cell_array = cellfun(@(x){x(st:sp)}, d(idx));
%values after running above. everything works until the last "cellfun" line, which isn't indexing how I want
% disp(idx') 2 3 4
% disp(d(idx)') 'atten 16.0 input -70.6 dBm' 'atten 0.0 input -67.5 dBm' 'atten 16.0 input -69.9 dBm'
% disp(st') 18 17 18
% disp(sp') 22 21 22
% disp(out_cell_array') '-70.6' '67.5 ' '-69.9' <-- is not indexing using the values of st and sp
%%%% I want this:
% out_cell_array = {d{2}(18:22); d{3}(17:21); d{4}(18:22)};
% disp(out_cell_array') '-70.6' '-67.5' '-69.9'
The x, st, and sp in your last cellfun don't match up. Try this:
x = d(idx); % extract the appropriate cells first
arrayfun(@(k)x{k}(st(k):sp(k)),(1:numel(st))','uni',false') % then extract the strings
Or, if you really want to use cellfun,
cellfun(@(x,st,sp){x(st:sp)}, d(idx),num2cell(st),num2cell(sp))