2017-10-28 117 views
1

我有一個單元格數組(arr_new),它包含數字和字符串,我想查找每列的平均值(並忽略字符串,因爲這些是指向我想在我的計算中忽略)使用Matlab。該數組是一個200x200的單元格數組,它是數字和字符串的組合。使用Matlab查找數字和字符串數組的平均值

我試圖用這樣的:

for k = 1:cols 
    Y(k) = mean(arr_new(k,:)); 
end 

但當然,它並沒有因爲字符串的工作。

任何幫助,將不勝感激。

回答

1
nCols = size(arr_new,2); 
Y = nan(1, nCols); % pre-allocate 
for k = 1:nCols 
    isNum = cellfun(@isnumeric, arr_new(:,k)); % find number in the column 
    Y(k) = mean(cell2mat(arr_new(isNum,k))); % convert to mat for mean 
end 

這裏有兩個技巧。一種是使用cellfun,另一種是cell2mat

+0

非常感謝。它工作得很好。 –

2

如果您有任何MATLAB R2015a (or later)統計和機器學習工具箱的,串/字符轉換爲NaN,然後就可以找到的平均轉換cell to a matrix後忽略這些值。

k = cellfun(@isnumeric, arr_new);  %finding the indices of the numeric values 
arr_new(~k)={NaN};      %replacing the rest of the indices with NaN 
%finding mean ignoring NaNs (which were chars/strings before) 
Y = mean(cell2mat(arr_new),'omitnan'); %for MATLAB R2015a or later 
% Use the following instead if you have R2014b or earlier with Stats and ML Toolbox: 
% Y = nanmean(cell2mat(arr_new)); 
+0

非常感謝!當我嘗試它時,它是成功的! –

相關問題