Apply function on specific rows
조회 수: 14 (최근 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.
댓글 수: 1
답변 (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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!