How to obtain average in a matrix without loop?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Sean de Wolski
am 7 Sep. 2012
Bearbeitet: Sean de Wolski
am 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
am 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.
Akzeptierte Antwort
Sean de Wolski
am 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!