Enumerate multi dimensional array

axes doesn’t include the value, unlike enumerate. And actually, it’s not enumerate you want, even for one-dimensional vectors. You should use pairs, since enumerate always starts counting at 1 no matter what sort of array you have (even 0-indexed arrays).

julia> a = randn(3,2)
3×2 Array{Float64,2}:
  0.446886    0.168215
 -0.0590402   1.89755
  0.0420936  -1.62462

julia> for (ind, val) in pairs(a)
       println(ind, ": ", val)
       end
CartesianIndex(1, 1): 0.4468857733868482
CartesianIndex(2, 1): -0.0590401519075785
CartesianIndex(3, 1): 0.04209357154257153
CartesianIndex(1, 2): 0.16821454509635914
CartesianIndex(2, 2): 1.8975549461332841
CartesianIndex(3, 2): -1.624623544140236

You can get (i, j) from calling Tuple(ind), but you should rather use the cartesian index directly:

function new_matrix(matrix)
    new_matrix = copy(matrix)
    for (ind, element) in pairs(matrix)
        (i, j) = Tuple(ind)
        new_matrix[ind] = i * j * matrix[ind]  # or ind[1]*ind[2] * matrix[ind]
    end
    return new_matrix
end
6 Likes