Matlab中如何利用cellfun对元胞数组字符串索引提取目标数值?
问题解决:用cellfun提取元胞数组中指定范围的字符串
问题原因
你最后一步cellfun未得到预期结果,是因为st和sp是长度为3的向量,但匿名函数@(x){x(st:sp)}处理单个字符串时,会把整个st和sp向量的索引组合都套用在当前字符串上,而非使用对应位置的单个索引值,导致提取结果混乱。
修正后的cellfun实现
cellfun支持多输入参数,只需将每个字符串对应的起始、结束索引单独传入,就能实现逐个对应提取:
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; % 从“input”右侧第6位开始索引 sp = cellfun(@(x) strfind(x, 'dBm'), d(idx)) - 2; % 从“dBm”左侧第2位结束索引 % 关键修正:将st、sp转为元胞数组,让每个字符串对应自己的索引 out_cell_array = cellfun(@(x,s,p) {x(s:p)}, d(idx), num2cell(st), num2cell(sp)); disp(out_cell_array') % 输出:'-70.6' '-67.5' '-69.9'
更简洁的替代方案:正则表达式
手动计算索引容易出错,用正则表达式可以直接匹配input和dBm之间的数值,代码更简洁可靠:
% 匹配input与dBm之间的正负小数 pattern = 'input\s+(-?\d+\.\d+)\s+dBm'; out_cell_array = regexp(d(idx), pattern, 'tokens', 'once'); % 若需要转为数值数组 out_numeric = cell2mat(out_cell_array);
内容的提问来源于stack exchange,提问作者Sanjo
相关产品推荐
相关产品推荐

