Skip to content

(otus algebra init)

Uri edited this page Aug 4, 2021 · 5 revisions

This functions accepts the same parameters as matrix:

(Zeros . args)

Makes a zeroed copy of provided vector/matrix/tensor. Arguments the same as for matrix function (for now, will be updated to same as for tensor function when be done). The original v/m/t remain unchanged.

> (Zeros 3 4)
#(#(0 0 0 0) #(0 0 0 0) #(0 0 0 0))

> (Zeros [1 2 3] 4)
#(#(0 0 0) #(0 0 0) #(0 0 0) #(0 0 0))

> (Zeros [1 2 3 4])
#(0 0 0 0)

(Zeros! v)

Initializes provided vector/matrix/tensor with zeros. The original v/m/t will change!

> (define m [1 2 3]
            [4 5 6])
> (print m)
#(4 5 6)
> (Zeros! m)
#(0 0 0)
> (print m)
#(0 0 0)

(Ones . args)

Same as Zeros, but with 1.

(Ones! v)

Same as Zeros!, but with 1.

(Fill v n)

Makes a copy of vector/matrix/tensor filled with n. n should be a number (0, 1, 777, 3/7 or 2+4i, etc.) or a no-arguments function. The original v/m/t remain unchanged.

> (Fill [1 2 3] 7)
#(7 7 7)

> (import (otus random!))
> (Fill
   [[3 4] [5 7]]
   (lambda () (rand! 144)))
#(#(42 23) #(79 55))

(Fill! v n)

Fills a vector/matrix/tensor with n. n should be a value (0, 1, 777, but not a 3/7 or 2+4i). The original v/m/t will change!

> (define m [[[1 2][3 4]]
             [[5 6][7 8]]
             [[9 5][3 3]]
             [[0 2][9 9]]])
> (print m)
#(#(#(1 2) #(3 4)) #(#(5 6) #(7 8)) #(#(9 5) #(3 3)) #(#(0 2) #(9 9)))

> (Fill m 777)
#(#(#(777 777) #(777 777)) #(#(777 777) #(777 777)) #(#(777 777) #(777 777)) #(#(777 777) #(777 777)))
> (print m)
#(#(#(1 2) #(3 4)) #(#(5 6) #(7 8)) #(#(9 5) #(3 3)) #(#(0 2) #(9 9)))

> (Fill! m 42)
#(#(#(42 42) #(42 42)) #(#(42 42) #(42 42)) #(#(42 42) #(42 42)) #(#(42 42) #(42 42)))
> (print m)
#(#(#(42 42) #(42 42)) #(#(42 42) #(42 42)) #(#(42 42) #(42 42)) #(#(42 42) #(42 42)))

(Index array function)

Maps a vector/matrix/tensor by indices.

Making a chessboard:

> (Index (Matrix 4 5)
     (lambda (x y)
        (if (eq? (mod (+ x y) 2) 0) 1 0)))
#(#(1 0 1 0 1) #(0 1 0 1 0) #(1 0 1 0 1) #(0 1 0 1 0))

> (Index (Tensor 2 3 4)
     (lambda (x y z)
        (if (eq? (mod (+ x y z) 2) 0) 1 0)))
#(#(#(0 1 0 1) #(1 0 1 0) #(0 1 0 1)) #(#(1 0 1 0) #(0 1 0 1) #(1 0 1 0)))```

Just print indices:
```scheme
> (Index (Tensor 2 3 4)
     (lambda (x y z)
        (print x " " y " " z)))
1 1 1
1 1 2
1 1 3
1 1 4
1 2 1
1 2 2
1 2 3
1 2 4
1 3 1
1 3 2
1 3 3
1 3 4
2 1 1
2 1 2
2 1 3
2 1 4
2 2 1
2 2 2
2 2 3
2 2 4
2 3 1
2 3 2
2 3 3
2 3 4
Clone this wiki locally