'How to update all diagonal values in Matrex matrix

I work with Elixir Matrex (https://hexdocs.pm/matrex/Matrex.html) and want to update or set all diagonals elements to zeros (and later to ones).

I tried:

matrix_size = 5
randommatrix = Matrex.random(matrix_size)

for index_i <- 1 .. matrix_size, do: randommatrix = Matrex.update(randommatrix, index_i, index_i, fn a -> 0 end)

#subsequent work with matrix that has all diagonal elements zero
#...

This approach updates randommatrix only "inside" comprehension and the subsequent code sees the randommatrix unchanged.

I think that I can do what I need through recursive function, however, is there any other efficient method (minimal computer time)? Thanks



Solution 1:[1]

If you don't want to use recursion, you could use the apply/2 method. This allows you to apply a function to every element of a matrix. The update function gets the respective value and index. This way we can easily update all values on the diagonal.

Example: For a 5x5 matrix the following indices are to be updated: [1, 7, 13, 19, 25]. So if we take the index modulo 6 (matrix_size + 1), the remainder is always 1.

matrix_size = 5
matrix = Matrex.random(matrix_size)
# Update diagonal to zero
Matrex.apply(matrix, fn val, index -> if rem(index, matrix_size+1) == 1 do 0 else val end)

Solution 2:[2]

Why don't you want to make it a recursion? I think that would be an elegant way to solve this problem.

Something like this (code is not tested):

update(matrix, 0), do: matrix
update(matrix, index) do
    update(
        Matrex.update(matrix, index, index, fn a -> 0 end),
        index-1
    )
end

Example call: udpate(matrix, 5)

First the elment at position (5,5) is updated. Thereby a new matrix is created. With this new matrix we go into recursion. Next, the element at position (4,4) is updated - and so on.

The termination condition is done with pattern matching on the second argument. So when counting down to 0, nothing more is done than returning the finished matrix.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve
Solution 2 Steve