Clear Filters
Clear Filters

Get new variable based on the average of a column - Matlab

1 view (last 30 days)
I have a cell array variable with 15 columns and about 200 000 rows. These cell array, is sorted by year (C1) and then by a code (C2). For instance, in this example in only present 3 years and 2 codes:
C1 C2 C3 C4 C5
1997 3 AA 3421 0.4
1997 11 AB 789 2.1
1998 3 FC 3421 0.1
1998 3 NU 3421 0.6
1998 11 AB 789 0
1998 11 NT 789 0.4
1999 3 NU 42 0.3
1999 11 NT 17 0.5
2000 3 FC 42 0.8
2000 3 NO 42 1.2
2000 11 NT 17 0.9
I would like to get a new variable giving me the average of the values in C5 for each different code in C2, in year t (e.g.: 1999) and 2 previous years (e.g.: 1997 & 1998), independently of the values/strings in columns C3 and C4. In this example I would obtain:
C2 C3 NEW
3 1997 - % There is no data prior to 1997 so I cannot calculate the average for year t, t-1 & t-2
11 1997 -
3 1998 -
11 1998 -
3 1999 0,35 %(0.4+0.1+0.6+0.3)/4
11 1999 0,75 %(2.1+0+0.4+0.5)/4
3 2000 0,6 %(0.1+0.6+0.3+0.8+1.2)/5
11 2000 0,45 %(0+0.4+0.5+0.9)/4
Can someone help? Thanks.
  4 Comments
Sara
Sara on 18 Jul 2014
How can you have C5 as number in matlab? You mean you actually have 0.4 and so on in your cell array (the comma is not the decimal sign in matlab)? The type influences how you treat variables, that's why I'm asking.
Maria
Maria on 18 Jul 2014
I am sorry. In Matlab I have the decimal sign. When I built the example I wrote 'commas' instead. I will edit it.

Sign in to comment.

Accepted Answer

Sara
Sara on 18 Jul 2014
See file
  4 Comments
Maria
Maria on 18 Jul 2014
I tried your code, it gives the following error:
Error using &
Matrix dimensions must agree.
I am running out of time now, but I will check what's wrong. I will let you know later on. Thanks
Sara
Sara on 18 Jul 2014
Works for me with the input provided. May want to attach the whole input to your post if the program fails.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!