在具有不同类型元素的单元格数组中查找字符串 [英] Find string in cell array with elements of different types
问题描述
我有一个接受可变参数的函数.这些参数是参数值对,因此varargin
是一个单元格数组,其中每个奇数索引元素都是一个字符串(参数),但是偶数索引元素可以是字符串,数字或字符串的单元格数组.我想在varargin
中找到特定字符串的索引.我有一个可行的解决方案,但是它两次使用arrayfun
;有没有更清洁/更快/更有效的方式在这种单元阵列中查找字符串?生成的index
将用于从varargin
中删除该元素和下一个元素.我想最大程度地减少新变量的创建.
I have a function that takes variadic arguments. These arguments are parameter-value pairs, so varargin
is a cell array in which every odd-indexed element is a string (the parameter), but the even-indexed elements can be a string, number, or cell array of strings. I want to find the index of a particular string in varargin
. I have a working solution, but it uses arrayfun
twice; is there a cleaner/faster/more effective way of find a string in such a cell array? The resulting index
will be used to remove that element and the following one from varargin
. I would like to minimize creation of new variables.
str_to_find = 'paramX'
finds = arrayfun(@(i) strfind(varargin{i},str_to_find), 1:length(varargin), 'UniformOutput', 0);
finds2 = arrayfun(@(i) ~iscell(finds{i}) && ~isempty(finds{i}), 1:length(finds));
index = find(finds2==1);
varargin(index)=[];
varargin(index)=[];
给出varargin
为{'paramA', 'valueA', 'paramB', 9, 'paramX', {'z','x','c'}
,然后finds
为[] [] [] [] [1] {1x3 cell}
,finds2
为0 0 0 0 1 0
,并且index
为5
.因此,我的解决方案可以满足我的需求,但这看起来很难看.我只会使用finds2
(即不创建index
)从varargin
中删除该元素,但是我还需要删除其后的那个元素.
Given varargin
is {'paramA', 'valueA', 'paramB', 9, 'paramX', {'z','x','c'}
, then finds
is [] [] [] [] [1] {1x3 cell}
, finds2
is 0 0 0 0 1 0
, and index
is 5
. So, my solution does what I need, but it just seems ugly. I would just use finds2
(i.e., not create index
) to delete that element from varargin
, but I also need to remove the one after it.
推荐答案
您可以使用内置函数strcmp
,该函数应该相当快:
You can use the built-in function strcmp
which should be fairly fast:
idx = strcmp(str_to_find, varargin);
这将为您提供所有与目标匹配的字符串的单元格的索引.
and that will give you an index to all cell elements that are strings matching the target.
然后,要修剪这些元素,可以使用
Then, for pruning those elements, you can use
varargin( or(idx, [0 idx(1:end-1)]) ) = [];
假设idx是一个行数组.
assuming that idx is a row array.
最后,您可能还需要运行一些格式检查,以确保用户未按错误的顺序(或参数名称与参数名称匹配)输入参数对,否则这种代码的行为会很奇怪
Finally, you may also want to run some format checks to make sure that the user has not entered argument-pairs in the wrong order (or with an argument name that matches the parameter name) otherwise this kind of code will behave strangely.
这篇关于在具有不同类型元素的单元格数组中查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!