Apply function on specific rows

Hi Everyone,
I am kind of new to MATLAB and have a problem. I used to use, S-Plus and they have a function called "tapply" and I think I am looking for something similar.
Here is the situation, I have time-series database, with a column representing month/year. I would like to apply "mean" function to those rows which have same month/year. For example, if there are 20 unique month/year values, i will have 20 different "mean" each representing, an average of that particular month/year.
Looking forward to responses. Thank you in advance.

1 commentaire

Fangjun Jiang
Fangjun Jiang le 29 Juil 2011
It should be quite easy if you provide some example data.

Connectez-vous pour commenter.

Réponses (2)

Walter Roberson
Walter Roberson le 29 Juil 2011

0 votes

You could use a "for" loop in the general case.
If you are computing a value for each row, you could use
TheValues = arrayfun(@(K) YourFun(YourVariable(K,:)), [list of rows])
For simple functions such as mean, and simple arrays, you can use
TheValues = mean(YourVariable([list of rows],:),2);
The ,2 part tells it to take the mean along the second dimension (rows)
KKR
KKR le 29 Juil 2011

0 votes

Thank you Walter, but I am little confused what is K? And what do you mean by list of rows?
Fangjun Jiang,
I have attached a sample data base. Please see if it helps.
Kaushal
date tr
1/1/2003 1.880878
1/1/2003 -19.07757
1/1/2003 -20.79946
1/1/2003 -10.12233
1/1/2003 -4.862288
4/1/2003 26.86057
4/1/2003 21.90327
4/1/2003 17.20895
4/1/2003 40.25018

1 commentaire

Walter Roberson
Walter Roberson le 30 Juil 2011
The K is the arglist in the anonymous function; see http://www.mathworks.com/help/techdoc/matlab_prog/f4-70115.html
A list of rows would be like [1 2 3 4 5] or [6 7 8 9] or 1:5 or 6:9 to apply to the designated rows. Your original question did not indicate that your data would always be consecutive so I was thinking that you might have to specify (e.g.) [1 2 6 8 10 11 15]
I do not know how to retrieve a particular row from a database. If the above data were presented in the form of a 9 x 2 cell array, then I would use code such as
mean(vertcat(data{1:6,2}))
To go beyond this, see unique() and ismember(), and look in the MATLAB File Exchange to see if John d'Errico's "consolidator" program is available.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Performance and Memory dans Centre d'aide et File Exchange

Question posée :

KKR
le 29 Juil 2011

Community Treasure Hunt

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

Start Hunting!

Translated by