Enumerate multi dimensional array

BTW, there are some not-so-nice things here. Don’t give your output matrix the same name as the function: new_matrix, that’s probably a bad idea. And a tip: use similar(matrix) instead of copy(matrix), it can be a lot faster.

Here’s some code that actually uses the pairs feature better:

function new_matrix(matrix)
    matrix_ = similar(matrix)
    for (ind, element) in pairs(matrix)
        matrix_[ind] = ind[1] * ind[2] * element 
    end
    return matrix_
end

And this code works for all array dimensionalities from 0 to N

function new_arr(arr)
    arr_ = similar(arr)
    for (ind, element) in pairs(arr)
        arr_[ind] = prod(Tuple(ind)) * element
    end
    return arr_
end
4 Likes