map

map(f, c...) -> collection

Transform collection c by applying f to each element. For multiple collection arguments, apply f elementwise.

julia> map((x) -> x * 2, [1, 2, 3])
3-element Array{Int64,1}:
 2
 4
 6

julia> map(+, [1, 2, 3], [10, 20, 30])
3-element Array{Int64,1}:
 11
 22
 33

Examples

julia> array = Int[1,2,3]
       map(x -> x + 1, array)
3-element Array{Int64,1}:
 2
 3
 4
julia> array = Int[1,2,3]
       map(x -> x * 2, array)
3-element Array{Int64,1}:
 2
 4
 6

julia> map((x) -> x^3, [1 2 3])
1x3 Array{Int64,2}:
 1      8       27
julia> function Foo(x,y)
                return 2(x+y)
            end
julia> map(Foo, [1 2 3], ones(1, 3))
1x3 Array{Float64,2}:
 4.0    6.0     8.0
  1. Apply a function to each element of an array:

    julia> arr = [1, 2, 3, 4, 5];
    julia> map((x) -> x * 2, arr)
    5-element Array{Int64,1}:
    2
    4
    6
    8
    10

    This example applies the anonymous function (x) -> x * 2 to each element of the array arr and returns a new array with the transformed values.

  2. Apply a function elementwise to multiple collections:

    julia> a = [1, 2, 3];
    julia> b = [10, 20, 30];
    julia> map(+, a, b)
    3-element Array{Int64,1}:
    11
    22
    33

    The + function is applied elementwise to the corresponding elements of arrays a and b, resulting in a new array with the sum of each pair of elements.

  3. Transform strings using a custom function:
    julia> words = ["apple", "banana", "orange"];
    julia> map((s) -> uppercase(s), words)
    3-element Array{String,1}:
    "APPLE"
    "BANANA"
    "ORANGE"

    The anonymous function (s) -> uppercase(s) is applied to each string in the words array, transforming them to uppercase.

Common mistake example:

julia> arr = [1, 2, 3];
julia> map((x) -> x * 2, arr, [4, 5, 6])
ERROR: MethodError: no method matching iterate(::Int64)

In this example, the number of elements in the input arrays (arr and [4, 5, 6]) is not the same. When using map with multiple collections, ensure that all collections have the same length to avoid such errors.

See Also

append!, delete!, deleteat!, empty!, endof, filter, filter!, gc, get!, getkey, haskey, insert!, isempty, keys, map, map!, merge, merge!, pop!, prepend!, push!, reduce, resize!, shift!, splice!, unshift!, values,

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: