Get new variable if a condition verifies in a cell
显示 更早的评论
I have a cell type variable with 4 columns and 500000 rows, sorted by c3 and then by c1. For example:
c1 c2 c3 c4
A={2008 'VLO' 1 22
2009 'VCEP' 1 2
2009 'VLO' 1 22
2010 'SMDO' 1 4
2007 'SHBZ' 12 8
2008 'WNI' 12 7
2009 'AMB' 12 18
2010 'CCE' 12 13 …}
For each different c3, and if c1 is equal to 2010 I am trying to have a new variable X, with the year, with c3 and with the average of the values in c3 from that year (2010)and the two previous years/rows (2009 and 2008).
In this example my output would be:
P= {2010 1 12,5 %(22+2+22+4)/4
2010 12 12,67} %(7+18+13)/3
Can someone help? Thank you.
采纳的回答
更多回答(1 个)
Andrei Bobrov
2014-8-14
编辑:Andrei Bobrov
2014-8-14
Aw = cell2mat(A(:,[1,3,4]));
x = unique(Aw(:,2));
n = numel(x);
out = [2010*ones(n,1),x,nan(n,1)];
y = 2008:2010;
for ii = 1:n
At = Aw(Aw(:,2) == x(ii),:);
if all(ismember(y,At(:,1)))
out(ii,end) = mean(At(ismember(At(:,1),y),3));
end
end
out = out(~isnan(out(:,3)),:);
类别
在 帮助中心 和 File Exchange 中查找有关 Get Started with MATLAB 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!