Calculating the value, excluding nan
4 次查看(过去 30 天)
显示 更早的评论
I was calculating the average stock return of each year using the following code, and it shows error. This is due to the nan value in the stock return column (column 7). I turned the nan values to zero and it works.
However this will affect the result. I want to calculate only the data without the nan value (if the return is nan, exclude that row from calculation). How can I do that?
for k=1993:2021
stockreturn(k-1992) = mean(data_crsp(y==k,7));
%1st element will correspond to 1993, 2nd - 1994 and so on
end
0 个评论
回答(2 个)
Matt J
2022-7-30
编辑:Matt J
2022-7-30
subset=1993<=y & y<=2021;
datasub=data_crsp(subset,7);
ysub=y(subset)-1992;
stockreturn=splitapply(@(z)mean(z,'omitnan'),datasub,ysub);
2 个评论
Matt J
2022-7-30
Yes, it is meant to replace the whole code including the loop. DId you try it?
"subset" is a logical idnex into the range of y that you were looping over.
Steven Lord
2022-7-31
Consider storing your data in a timetable array, with the dates associated with your data stored as a datetime array. If you do this, you can use the retime function to calculate the mean of the data, specifying the anonymous function @(x) mean(x, 'omitnan') as the 'Method' in your call.
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!