Apply function on specific rows
15 次查看(过去 30 天)
显示 更早的评论
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.
回答(2 个)
Walter Roberson
2011-7-29
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)
0 个评论
KKR
2011-7-29
1 个评论
Walter Roberson
2011-7-30
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!