MatLab Looping Script with varying rows

1 view (last 30 days)
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!

Accepted Answer

Cedric
Cedric on 28 Oct 2013
Edited: Cedric on 28 Oct 2013
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 Comments
Don Chao
Don Chao on 2 Nov 2013
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!
Cedric
Cedric on 5 Nov 2013
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))) ) ;

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!