mapreducedim
mapreducedim(f, op, A, dims[, initial])
Evaluates to the same as reducedim(op, map(f, A), dims, f(initial)), but is generally faster because the intermediate array is avoided.
Examples
-
Apply a function to each element and reduce along dimensions:
julia> A = [1 2 3; 4 5 6; 7 8 9]; julia> mapreducedim(x -> x^2, +, A, 2) 3-element Array{Int64,1}: 14 77 194This example squares each element of matrix
Aand then sums the squared values along the second dimension (columns). -
Perform element-wise operation and reduce along specified dimensions:
julia> A = [1 2 3; 4 5 6; 7 8 9]; julia> mapreducedim(x -> x^2, *, A, 1) 3-element Array{Int64,1}: 28 80 162It squares each element of matrix
Aand then multiplies the squared values along the first dimension (rows). - Specify an initial value for reduction:
julia> A = [1 2 3; 4 5 6; 7 8 9]; julia> mapreducedim(x -> x^2, max, A, 2, 0) 3-element Array{Int64,1}: 9 36 81In this example, the initial value for reduction is set to 0. The function squares each element of matrix
Aand then finds the maximum squared value along the second dimension (columns), starting from the initial value.
Common mistake example:
julia> A = [1 2 3; 4 5 6; 7 8 9];
julia> mapreducedim(x -> x^2, +, A, 3)
ERROR: DimensionMismatch("dimension out of range")
In this example, the specified dimension is out of range for matrix A. It's important to provide valid dimensions that exist in the array to avoid such errors. Double-check the dimensions of the array and ensure they are within the appropriate range when using mapreducedim.
See Also
foldl, foldr, mapfoldl, mapfoldr, mapreduce, mapreducedim,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.