Using Accumarray with @maxk instead of @max?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ayman Al-Sukhon
am 16 Dez. 2019
Kommentiert: Ayman Al-Sukhon
am 17 Dez. 2019
Hi,
Say you have three vectors:
a = [1;2;3;4;5;1;3;1;4];
b = [100;200;300;400;500;400;300;200;100];
c = [123;456;221;111;800;1000;10;25;150];
And you use accumarray so that:
maxval = sparse(accumarray(a(:,1),max(b,c),[],@max))
You get:
maxval =
(1,1) 1000
(2,1) 456
(3,1) 300
(4,1) 400
(5,1) 800
Now lets, say I have a whole lot of variables for each subs (something like 2000 each), and I want the average of the top 3 values using the same method. How can I accomplish this? For example, in the same problem, I want my output to be:
The top three values with subs 1 are: 100,400 and 200, so their average is 233.33 and the first row in my sparse matrix is:
maxval =
(1,1) 1000
and so on.
Is it maybe possible to use maxk as a function handle?
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 16 Dez. 2019
accumarray(a(:,1), max(b,c), [], @(v) mean(maxk(v,3)), 0, true) %final parameter is sparse flag
3 Kommentare
dpb
am 17 Dez. 2019
@() is the preamble to define an anonymous function. The v is the dummy argument variable name Walter chose; you'll see it reflected in the argument to maxk().
All the details about anonymous functions is in the documentation under the general subject of functions.
Weitere Antworten (1)
dpb
am 16 Dez. 2019
Bearbeitet: dpb
am 16 Dez. 2019
Don't see anyway around with accumarray because the VAL parameter must be 1:1 with rows of SUBS; use findgroups/splitapply or varfun (altho latter must be table or timetable).
g=findgroups(a);
mnk=splitapply(@(x) mean(maxk(x,3)),b,g);
yields
>> mnk =
233.3333
200.0000
300.0000
250.0000
500.0000
>>
7 Kommentare
dpb
am 16 Dez. 2019
What it looked like to me, too, Walter.
Your's works for the specific instance (or anywhere sum is the needed intemediary); however in the followup here I was thinking of the more general cases where the function needs the elements rather than a single result.
Siehe auch
Kategorien
Mehr zu Matrix Indexing 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!