I am writing a looping or recursive script to calculate the yearly averages from monthly stock prices from a database. However, each company has varying number of rows/entries, making it difficult to autonomously calculate the average.
I need to have the script calculate the average as long as the rows/entries are from the same company name. Any help is greatly appreciated!

 채택된 답변

Cedric
Cedric 2013년 10월 28일
편집: Cedric 2013년 10월 28일

1 개 추천

It is difficult to answer, because we don't know what you mean by database, or why you need recursivity (why a FOR loop is not enough, of why you even need such a loop).
If you are truly dealing with a database, you'll SELECT the relevant company and you can just use MEAN to compute the average (it will work with any data size). If you need/want to get all companies in one shot and then compute the average per company, you can proceed as follows. Note that I assume that companies have IDs (defined by the DBM, or by yourself) which are integers starting at 1.
I define a fake data set for the purpose of this example..
>> data = [randi(3,10,1), 20*rand(10,1)]
data =
3.0000 3.1523
3.0000 19.4119
1.0000 19.1433
3.0000 9.7075
2.0000 16.0056
1.0000 2.8377
1.0000 8.4352
2.0000 18.3147
3.0000 15.8441
3.0000 19.1898
Here, the first column is the company ID, and the second the stock price. Now we compute means using ACCUMARRAY and the company ID as vector of indices..
>> allMeans = accumarray( data(:,1), data(:,2), [], @mean )
allMeans =
10.1388
17.1602
13.4611
You see that we get a vector of three means, one for each company. ACCUMAARAY computes the sum by default, unless we pass the function that it has to use for accumulation as 4th argument. This is what we are doing, passing a handle on function MEAN (which is what we want to compute).
If it is not what you wanted, you'll have to make your question more precise about what you have and what you need.

댓글 수: 2

Don Chao
Don Chao 2013년 11월 2일
Hi Cedric,
Thank you so much for helping me out. That works great! How would I create a new matrix that contains the output means and the corresponding company ID's?
Again, thank you so much, you are a great help!
You know that the company IDs are 1, 2, 3 in this case, as they are used as indices to produces of the vector allMeans. If you needed a count of occurrence of company IDs, you could accumulate a vector of ones the same way we accumulated data, but using the SUM function instead of MEAN. As SUM is the default behavior of ACCUMARRAY, we achieve this as follows:
counts = accumarray( data(:,1), ones(size(data(:,1))) ) ;

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

질문:

2013년 10월 28일

댓글:

2013년 11월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by