使用Matlab查找数字和字符串数组的平均值
问题描述:
我有一个单元格数组(arr_new
),它包含数字和字符串,我想查找每列的平均值(并忽略字符串,因为这些是指向我想在我的计算中忽略)使用Matlab。该数组是一个200x200的单元格数组,它是数字和字符串的组合。使用Matlab查找数字和字符串数组的平均值
我试图用这样的:
for k = 1:cols
Y(k) = mean(arr_new(k,:));
end
但当然,它并没有因为字符串的工作。
任何帮助,将不胜感激。
答
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
。
答
如果您有任何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
非常感谢!当我尝试它时,它是成功的! –
非常感谢。它工作得很好。 –