2016-09-23 18 views
0

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

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 

否则,在这里可以做矢量化吗?

+0

你为什么不过滤掉你的字符串和NaN? – GameOfThrows

+0

看看Suever的答案,它解决了这个问题,并且相当于 – GameOfThrows

回答

0

您可以通过检查每个元素是否为数字来创建逻辑数组。然后用它对包含数字数据的单元数组的子集执行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和更新)更好的性能。

+1

值得注意的是,在更新版本的MATLAB中等效循环方法更快([gist](https://gist.github.com/sco1/1a0242681a43569e70c1f7ad82352b16)) – excaza

+0

优秀的解决方案 – Augusti

+0

注意@excaza&Suever。感谢名单。 – Augusti