识别一行中的单元格输入

Recognizing a cell input in one line

考虑以下输入为

的函数
>> b.a = 1    
b =     
    a: 1

>> c = {'this' 'cell'}    
c =     
    'this'    'cell'

>> d = [1 2 3]    
d =    
     1     2     3

可以通过多种方式调用输入,例如 testfunction(b,d,c) testfunction(d,c,b) 等我想获取单元格输入并从中检索一些数据

function testfunction(varargin)
for i =1:numel(varargin)
    if(iscell(varargin{i}))
        fprintf('The input number %d is a cell!\n',i)
    end
end

它可以识别变量输入是否是一个单元格,但是有什么优雅的方法可以做到这一点吗?因为 iscell 不 return 支持索引,我也使用 class() 但它 returns class of varargin 而不是输入

不确定在这种情况下是否避免了循环,但这应该可以解决问题。

testfunction(b,c,d) 
testfunction(b,c,d,c)
testfunction(b,d)


function testfunction(varargin)

if any(cellfun(@(x) iscell(x),varargin))
fprintf(['The input(s) ' num2str(find(cellfun(@(x) iscell(x),varargin))) ' is (are) cell \n']);
end

end

这里的主要问题不是性能,而是可读性和漂亮的代码。

我建议您创建一个单独的函数来检查单元格的位置,然后在主函数中调用该函数。这样您就可以在一行中检查单元格的位置。它简单、快速且非常易于阅读。由于您可以在编辑器中保存函数并关闭脚本,这就像调用内置的单行代码一样。该函数还可以进行其他输入检查。

示例函数:

function idx = cell_index(C)
idx = 0;
if isempty(C)
    warning('No input was given.')
else
    for ii = 1:numel(C)
        if(iscell(C{ii}))
            idx = ii;
        end
    end
end
if idx == 0
    warning('The input contained no cells.')        
end
end

现在您可以在主函数中执行以下操作:

function output = main_function(varargin)
    idx = cell_index(varargin)
    fprintf('The input number %d is a cell!\n', idx)
    %
    % or fprintf('The input number %d is a cell!\n, cell_index(varargin))

% Rest of code

** 循环与其他方法:**

让我们试试几个功能:

方法 1:循环

这是最快的:

function s = testfunction1(varargin)    
for ii = 1:numel(varargin)
    if(iscell(varargin{ii}))
        s = sprintf('The input %i is a cell!\n', ii);
    end
end
end

方法二:cellfun

这是最慢且最难阅读的 (IMO):

function s = testfunction2(varargin)    
if any(cellfun(@(x) iscell(x),varargin))
    s = sprintf('The input %s is a cell\n', num2str(find(cellfun(@(x) iscell(x),varargin))));
end    
end

方法三:cellfun

假设您不需要循环,这是最简单的一个

function s = testfunction3(varargin)    
x = find(cellfun(@(x) iscell(x),varargin));
if ~isempty(x)
    s = sprintf('The input %i is a cell \n',x);
end    
end

以下基准测试是在新的 JIT 引擎之前使用 Matlab R2014b 执行的!

f = @() testfunction1(b,c,d);
g = @() testfunction2(b,c,d);
h = @() testfunction3(b,c,d);
timeit(f)
ans =
   5.1292e-05

timeit(g)
ans =
   2.0464e-04

timeit(h)
ans =
   9.7879e-05

总结:

如果您想使用无循环方法,我建议使用最后一种方法(第二个 cellfun 版本)。这只执行一次 find 和一次调用 cellfun。因此它更容易阅读,而且速度更快。