2016-09-23 22 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