Get new variable if a condition verifies in a cell
Show older comments
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.
Accepted Answer
More Answers (1)
Andrei Bobrov
on 14 Aug 2014
Edited: Andrei Bobrov
on 14 Aug 2014
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)),:);
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!