accumarray

时间:2022-03-31 12:19:54
 Example 

 Create a -by- vector and sum values for repeated -D subscripts:
val = :;
subs = [; ; ; ; ]
subs = A = accumarray(subs, val)
A =
% A() = val() =
% A() = val()+val() = + =
% A() =
% A() = val()+val() = + = The order of the subscripts matters:
val = :;
subs=[ ; ; ; ; ; ];
B1 = accumarray(subs,val,[],@(x)sum(diff(x))) B1 = - - Example Create a -by--by- array and sum values for repeated -D subscripts:
val = :;
subs = [ ; ; ; ; ]; A = accumarray(subs, val)
A(:,:,) = A(:,:,) = Example Create a -by--by- array, and sum values natively:
val = :;
subs = [ ; ; ; ; ]; A = accumarray(subs, int8(val), [], @(x) sum(x,'native'))
A(:,:,) = A(:,:,) = class(A)
ans =
int8 Example Pass multiple subscript arguments in a cell array. Create a -element vector V:
V = :; Create three -element vectors, one for each dimension of the resulting array A. Note how the indices of these vectors determine which elements of V are accumulated in A:
% index index => V()+V() => A(,,)
% | |
rowsubs = [ ];
colsubs = [ ];
pagsubs = [ ];
% |
% index => V() => A(,,)
%
% A(,,) = V() + V() = + =
% A(,,) = V() = Call accumarray, passing the subscript vectors in a cell array:
A = accumarray({rowsubs colsubs pagsubs}, V)
A(:,:,) =
% A(,,) is A(:,:,) = % A(,,) is Example Create an array with the max function, and fill all empty elements of that array with NaN:
val = :;
subs = [ ; ; ; ; ]; A = accumarray(subs, val, [ ], @max, NaN)
A =
NaN NaN NaN
NaN NaN Example Create a sparse matrix using the prod function:
val = :;
subs = [ ; ; ; ; ]; A = accumarray(subs, val, [ ], @prod, , true)
A =
(,)
(,)
(,) Example Count the number of entries accumulated in each bin:
val = ;
subs = [ ; ; ; ; ]; A = accumarray(subs, val, [ ])
A = Example Create a logical array that shows which bins will accumulate two or more values:
val = :;
subs = [ ; ; ; ; ]; A = accumarray(subs, val, [ ], @(x) length(x) > )
A = Example Group values in a cell array:
val = :;
subs = [ ; ; ; ; ]; A = accumarray(subs, val, [ ], @(x) {x})
A =
[ ] [] [] []
[2x1 double] [] [2x1 double] [] A{}
ans =

Examples