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];
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…