Getting NaN as the mean of a row that contains no NaN values, Inf values, 0/0 values
5 次查看(过去 30 天)
显示 更早的评论
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));
end
I would really appreciate your help. Thank you in advance.
1 个评论
Alberto Cuadra Lara
2021-10-30
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');
end
采纳的回答
DGM
2021-10-30
编辑:DGM
2021-10-30
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))
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)
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].'
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!