仅舍入具有不同数据类型的元胞数组中的数字元素

Round only numeric elements in cell array with different data types

我有一个包含不同类型变量(双精度和字符串)的单元格,我想对单元格中的数字元素进行舍入。 round 函数只能用于数组而不是单元格,所以我正在尝试使用 cell2mat - 但如果单元格中的元素类型不同,则不能使用此函数。

知道如何舍入此单元格中的数字元素吗?当然我不想循环单元格元素。

您想利用 str2double 将非数字类型转换为 NaN 的能力。

假设你有这样一个单元格:

 A = {'1.999','3.1415','pie','??'}
 B = round(str2double(A))

 B =

 2     3   NaN   NaN

正如 Adriaan 所提到的,这可以通过 cellfun:

来完成
function testCell = q38476362

  testCell = {'t','h',1.004,'s',[],'i',4.99,[],'a',[],'ce',10.8};
  isnum = cellfun(@(x)~isempty(x) & isnumeric(x),testCell);
  testCell(isnum) = num2cell(round([testCell{isnum}],0));

testCell = 

    't'    'h'    [1]    's'    []    'i'    [5]    []    'a'    []    'ce'    [11]

如果您的元胞数组在 string 的位置和 double 的位置方面是随机的,那么除了 loop/cellfun/[= 之外您无能为力17=]。但是,如果存在一些周期性(例如 "a string is always followed by two double entries"),您可以构建一些索引向量,无需迭代(显式或隐式)即可获得值。