필터 지우기
필터 지우기

Calculating the value, excluding nan

조회 수: 6 (최근 30일)
King To Leung
King To Leung 2022년 7월 30일
답변: Steven Lord 2022년 7월 31일
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

답변 (2개)

Matt J
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
King To Leung
King To Leung 2022년 7월 30일
Thank you for your reply!
Is this code able to replace all of the codes that i provide? No for loop is needed?
What does subset means?
Also, what does this mean "@(z)mean(z,'omitnan')" ?
A bit more information, I was finding the return of each year, and the date data is in column 2, and the return data in column 7.
Matt J
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.
"@(z)mean(z,'omitnan')" is an anonymous function.

댓글을 달려면 로그인하십시오.


Steven Lord
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.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by