我有一个包含数字和字符串的单元格数组(arr_new
),我想使用 Matlab 找到每列的平均值(并忽略字符串,因为这些是我想在计算中忽略的点)。该数组是一个 200x200 的单元格数组,它是数字和字符串的组合。
我尝试使用它:
for k = 1:cols
Y(k) = mean(arr_new(k,:));
end
但是,当然,由于字符串的原因,它不起作用。
任何帮助将不胜感激。
如果您有任何 MATLAB R2015a(或更高版本)或统计和机器学习工具箱,请将字符串/字符转换为NaN
,然后在将单元格转换为矩阵后找到忽略这些值的平均值。
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));
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
。