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!