Find mean of an array with both numbers and strings with Matlab

試著忘記壹切 提交于 2019-12-13 00:28:08

问题


I have a cell array (arr_new) that includes both numbers and strings and I want to find the mean value of each column (and ignoring the strings because those are points that I want to ignore in my calculation) using Matlab. The array is a 200x200 cell array and it is a combination of numbers and strings.

I tried to use this:

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

But of course, it did not work because of the strings.

Any help would be appreciated.


回答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

There are two tricks here. One is the use of cellfun, and the other is cell2mat.




回答2:


If you have any of MATLAB R2015a (or later) or Statistics and Machine Learning Toolbox, convert the strings/chars to NaN and then it is possible to find the mean ignoring those values after converting the 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)); 


来源:https://stackoverflow.com/questions/46995427/find-mean-of-an-array-with-both-numbers-and-strings-with-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!