Reputation: 117
I have an collection of arrays of the following way:
arr = Array{Array{Int64,1},1}( [ [1,2,3] , [4,5,6] , [7,8,9] ] )
I want to define a new aray sum
such that sums[i] = sum(arr[i])
but in a dynamic way such that if I change an element of arr[i]
, sums[i]
changes automatically. For example:
julia> sums
3-element Array{Int64,1}:
6
15
24
julia> arr[1][1] = 3
3
julia> sums
3-element Array{Int64,1}:
8
15
24
Is this possible to do? If so, how can I do it?
Upvotes: 0
Views: 66
Reputation: 5583
You can use MappedArrays
. MappedArrays
provide a "view" M
of an array A
so that M[i] = f(A[i])
. All you need to do add MappedArrays
package by ]add MappedArrays
and start using it with sum
function. Note that the transformation is lazy, meaning that it will compute the values in M
when you try to access them. Therefore, after an update to A
, you will see the change in M
when you access entries of M
.
julia> using MappedArrays
julia> arr = [ [1,2,3] , [4,5,6] , [7,8,9] ]
3-element Array{Array{Int64,1},1}:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
julia> M = mappedarray(sum, arr)
3-element mappedarray(sum, ::Array{Array{Int64,1},1}) with eltype Int64:
6
15
24
julia> arr[1][2] = 10
10
julia> M
3-element mappedarray(sum, ::Array{Array{Int64,1},1}) with eltype Int64:
14
15
24
Upvotes: 1