【问题标题】:cellfun with conditionals in MATLAB在 MATLAB 中带条件的 cellfun
【发布时间】:2016-09-23 14:17:38
【问题描述】:

是否可以使用带有条件的 cellfun。例如,我有一个 144x53 单元格数组,其中前四列是字符串类型,其余的是浮点数。但是,在数字中,有空单元格。我想知道是否可以将 cellfun(@(x)sqrt(x), cellarray) 与我的数组一起使用。众所周知,由于字符串和空单元格,这是不可能的。否则,这是我使用的解决方案,

for n = 1:length(results)
    for k = 1:length(results(1,:))
        if ~isstr(results{n,k})
            results{n, k} = sqrt(results{n,k});
        end
    end
end

否则,是否可以在这里进行矢量化?

【问题讨论】:

  • 你为什么不过滤掉你的字符串和NaN?
  • 看Suever的回答,解决了,等价

标签: matlab vectorization


【解决方案1】:

您可以通过检查每个元素是否为数字来创建逻辑数组。然后使用它对包含数值数据的元胞数组子集执行cellfun 操作。

C = {1, 2, 'string', 4};

% Logical array that is TRUE when the element is numeric
is_number = cellfun(@isnumeric, C);

% Perform this operation and replace only the numberic values
C(is_number) = cellfun(@sqrt, C(is_number), 'UniformOutput', 0);

%   1   1.4142    'string'    2

正如@excaza 所指出的,您也可以考虑将其保留为循环,因为它在较新版本的 MATLAB(R2015b 和更新版本)上性能更高。

【讨论】:

  • 值得注意的是,等效循环方法在较新版本的 MATLAB 中更快 (gist)
  • 优秀的解决方案
  • 注意@excaza & Suever。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-10-28
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 2012-09-19
  • 2014-08-03
  • 1970-01-01
相关资源
最近更新 更多