Getting NaN as the mean of a row that contains no NaN values, Inf values, 0/0 values

2 views (last 30 days)
Dear MATLAB experts,
I'm trying to calculate the mean values of each row of a table, but I keep on getting NaN as the value of the mean of each row.
I don't understand why I'm getting this error, since all values are doubles and there are no zero values / infinite values in the dataset. My code is the one below. I've also attached capmEstimates90 to this post.
capmEstimates90 = table2array(capmEstimates90)
capmEstimates90Stats = [];
% Calculating statistics
for i=1:height(capmEstimates90)
capmEstimates90Stats(1,i) = mean(capmEstimates90(:,i));
I would really appreciate your help. Thank you in advance.
  1 Comment
Alberto Cuadra Lara
Alberto Cuadra Lara on 30 Oct 2021
I do not obtain NaN values, but you can exclude Nan values using omitnan.
capmEstimates90 = table2array(capmEstimates90);
% Calculating statistics
for i=length(capmEstimates90(:,1)):-1:1 % Preallocate variable
capmEstimates90Stats(1,i) = mean(capmEstimates90(:,i), 'omitnan');

Sign in to comment.

Accepted Answer

DGM on 30 Oct 2021
Edited: DGM on 30 Oct 2021
Not sure if that's really supposed to be a wide table. You say you're calculating row means, but you're calculating column means instead. If your table is supposed to be transposed, then just transpose it. At any rate, there's no need for loops.
load capmEstimates90.mat
capmEstimates90 = table2array(capmEstimates90);
% let's say you want several different stats (examples)
columnmin = min(capmEstimates90,[],1); % min of each column
columnmax = max(capmEstimates90,[],1); % max of each column
columnmeans = mean(capmEstimates90,1); % mean of each column
columnnans = sum(isnan(capmEstimates90),1); % number of NaNs in each column
columnmeans2 = mean(capmEstimates90,1,'omitnan'); % mean of each column, ignoring NaN
% if you want to put them in one big array
outputstats = [columnmin; columnmax; columnmeans; columnnans; columnmeans2];
Yes, there are NaNs in there.
numberofnans = nnz(isnan(capmEstimates90))
numberofnans = 92
If you're truly doing things by row instead of by column, contrary to the code you posted, then yes, each row has at least one NaN.
nansperrow = sum(isnan(capmEstimates90),2)
nansperrow = 6×1
8 8 19 19 19 19
Though if you're doing things by column as described, most columns contain no NaNs, and no column contains more than six NaNs.
[counts edges] = histcounts(sum(isnan(capmEstimates90),1),'binmethod','integer');
nanspercol_instances = [edges(2:end)-0.5; counts].'
nanspercol_instances = 7×2
0 1851 1 0 2 0 3 0 4 11 5 0 6 8

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!