Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

matplotlib - MATLAB - past variances

I have a table that looks like this:

firm id     year      profit
1           2000      10
1           2001      20
1           2002      15
2           1999      40
2           2000      55
2           2001      35
2           2002      65
3           2001      5
3           2002      20
3           2003      10

And I want to estimate the var of the past years' firm profits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that your table is already sorted by "Firm ID" and by "Year", and that there's only one entry for each year, you can loop through each firm:

profitVar = [];
ids = unique(yourTable.firmId); % id of each firm

% Loop through the firms
for i = 1:length(ids) 
    id = ids(i);
    subData = find(yourTable.firmId == id); % get the data from the given firm only

    % Loop through the years
    for j = 1:length(subData)
        profitVar = [profitVar; var(yourTable.profit(subData(1:j-1)))];
    end

end
yourTable = addvars(yourTable, profitVar);

Note that this returns NaN only for the first year, and not the second year due to the fact that it is calculating the variance of the previous one (which will thus always be zero). If this is a problem, you could just insert an exception in the inner loop, something like if (j == 2) profitVar = [profitVar; NaN];.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...