I have a cell array containing numbers and strings. Can someone help me with a code that can calculate the mean of the numbers in each row?
Mix = {
'U' [4.7506e+05] [5.0141e+05] [5.4067e+05] [ 542976] [5.7124e+05]
[3.9810e+05] [4.4926e+05] 'U' [ 531440] [5.3655e+05] 'O'
[3.0915e+05] [3.6336e+05] [3.7107e+05] [3.8252e+05] [3.3988e+05] [4.3384e+05]
'U' 'U' 'U' 'O' 'U' [3.7107e+05]
'U' [3.7107e+05] 'U' [3.8252e+05] 'U' 'O' }
I did solve it with some help from a previous question: Find mean of an array with both numbers and strings with Matlab
Solution:
for k = 1:num
isNum = cellfun(@isnumeric, Mix(k,:)); % find number in the row
Y(k,1) = mean(cell2mat(Mix(k,isNum))); % convert to mat for mean
end
Here's a way:
Y = mean(str2double(cellfun(@num2str, Mix, 'UniformOutput', false)), 2, 'omitnan');
This works as follows:
cellfun(@num2str, Mix, 'UniformOutput', false)
converts each cell to a string.str2double(...)
converts each cell into a number. This gives NaN
for cells that didn't originally contain a number. The result is a standard, numeric array.mean(..., 2, 'omitnan')
computes the mean of each row ignoring NaN
values.Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments