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.
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
.
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));