使用Matlab查找包含数字和字符串的数组的平均值

时间:2017-10-28 23:16:18

标签: arrays string matlab mean

我有一个包含数字和字符串的单元格数组(arr_new)我希望找到每列的平均值(并忽略字符串,因为这些是我想在计算中忽略的点)使用Matlab。该阵列是一个200x200的单元阵列,它是数字和字符串的组合。

我试着用这个:

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

但是,当然,由于字符串,它不起作用。

任何帮助都将不胜感激。

2 个答案:

答案 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)); 

答案 1 :(得分: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