# 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

1. 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
194``````

This example squares each element of matrix `A` and then sums the squared values along the second dimension (columns).

2. 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
162``````

It squares each element of matrix `A` and then multiplies the squared values along the first dimension (rows).

3. 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
81``````

In this example, the initial value for reduction is set to 0. The function squares each element of matrix `A` and 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.

*Required Field
Details

Checking you are not a robot: