Matlab cellfun,如何对每个元素上的字符串应用索引?

问题描述 投票:0回答:1

我在使用 cellfun 函数对元胞数组中包含的字符串进行索引时遇到问题。我有一个包含各种内容字符串的元胞数组,我试图在以下示例中提取单词“input”和“dBm”之间的数字,其中感兴趣的行始终具有单词“atten”。 (我的实际用法有几十行,但这是一个简化的例子)。我可以使用“contains”函数获取包含“atten”的单元格的索引,该函数按预期工作。我还可以使用 cellfun 内的“strfind”函数获取要提取的每个单元格中的索引,这些索引在下面显示为变量“st”和“sp”。
但我无法使用“st”和“sp”值来提取感兴趣的数字,在本例中为-70.6、-67.5 和-69.9。使用 cellfun 可以实现这种类型的索引吗?或者我应该只使用 for 循环? 底部的注释代码显示了我当前在 out_cell_array 中获取的值,以及我要获取的内容。

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'
matlab indexing cell-array
1个回答
0
投票

上一个 cellfun 中的 x、st 和 sp 不匹配。试试这个:

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
© www.soinside.com 2019 - 2024. All rights reserved.