How to obtain average in a matrix without loop?

4 views (last 30 days)
In matrix A, I want to create a new column that contains the yearly average of the 5th column for each stations. The columns from left to right are: station, year, month, day, value. I want to avoid loops if possible.
A= [10 2000 1 1 1.5;
10 2000 1 3 1.1;
...
20 2000 1 1 1.2;
20 2000 1 2 1.4;
...
10 2001 1 1 1.1;
10 2001 1 4 1.3;
...
]
B= [10 2000 1 1 1.5 1.2;
10 2000 1 3 1.1 1.2;
...
20 2000 1 1 1.2 1.4;
20 2000 1 2 1.4 1.4;
...
10 2001 1 1 1.1 1.1;
10 2001 1 4 1.3 1.1;
...
]
so I want to make B in which the 6th column is yearly average of 5th column for each station.
thanks!
  6 Comments
Sean de Wolski
Sean de Wolski on 7 Sep 2012
Edited: Sean de Wolski on 7 Sep 2012
It means that you can fix the end result size if you want it to be bigger in the event that subs does not cover data at that size.
Let's say I have:
x = accumarray([1;2;1],ones(3,1))
But I always want the result to be 5x1 even if I don't have any 5s in my subs vector:
x = accumarray([1;2;1],ones(3,1),[5 1])
How could this be useful?
f() expects x to be a 5x1. I pull unique values from another vector but it turns out that there are only four unique values. The first implementation will return a 4x1 and would break f().
Matt Fig
Matt Fig on 7 Sep 2012
I concur, Jan! Every time I know intuitively that ACCUMARRAY would work in a given situation, I have to re-read the doc. Then I have to work through a few of the doc examples to remember how to interpret what the doc says. Then I can proceed to use the function, if I am lucky and don't have to re-read the doc. And English is my native tongue (I can't imagine trying to figure this function out otherwise)!
It is a useful function, but I usually spend more time trying to figure out how to apply it to the problem at hand as I would just writing the FOR loops. I cannot tell you how many times I have seen this error message:
Error using accumarray
Second input VAL must be a vector with one element for each row in SUBS, or a scalar.
It is one of the few MATLAB error messages I have memorized and that I expect to see the first time I try that function on a given day.

Sign in to comment.

Accepted Answer

Sean de Wolski
Sean de Wolski on 6 Sep 2012
A= [10 2000 1 1 1.5;
10 2000 1 3 1.1;
20 2000 1 1 1.2;
20 2000 1 2 1.4;
10 2001 1 1 1.1;
10 2001 1 4 1.3];
[~,~,idxA] = unique(A(:,1:2),'rows');
means = accumarray(idxA,A(:,4),[],@mean);
B = [A means(idxA)]
But your example does not actually make it look like B contains the means of column four for the unique combinations of columns 1/2.
  2 Comments
Jan
Jan on 6 Sep 2012
Perhaps "A(:,4)" -> "A(:,5)", but this will not create B also.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!