Skip to content

Commit

Permalink
add/2, new/3
Browse files Browse the repository at this point in the history
  • Loading branch information
versilov committed Jun 1, 2018
1 parent b23c55f commit f0731f8
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
39 changes: 39 additions & 0 deletions lib/matrex/array.ex
Expand Up @@ -14,6 +14,30 @@ defmodule Matrex.Array do
@type array :: %Array{data: binary, type: atom, shape: tuple, strides: tuple}
@type t :: array

@spec add(array, array) :: array
def add(%Array{data: data1, shape: shape, type: type}, %Array{
data: data2,
shape: shape,
type: type
}) do
%Array{
data: add_data(data1, data2, type),
shape: shape,
strides: strides(shape, type),
type: type
}
end

defp add_data(<<>>, <<>>, _), do: <<>>

defp add_data(
<<e1::float-little-32, rest1::binary>>,
<<e2::float-little-32, rest2::binary>>,
:float
) do
<<e1 + e2::float-little-32, add_data(rest1, rest2, :float)::binary>>
end

@spec at(array, index, index) :: element
def at(%Array{} = array, row, col), do: at(array, {row, col})

Expand Down Expand Up @@ -53,6 +77,21 @@ defmodule Matrex.Array do
defp binary_to_text(<<e::float, rest::binary>>, :double),
do: "#{e} " <> binary_to_text(rest, :double)

@spec new([element], tuple) :: array
def new(list, shape, type \\ :float) do
%Array{
data: list_to_binary(list, type),
shape: shape,
strides: strides(shape, type),
type: type
}
end

defp list_to_binary([], _), do: <<>>

defp list_to_binary([e | tail], type),
do: <<e::float-little-32, list_to_binary(tail, type)::binary>>

@spec random(tuple, type) :: array
def random(shape, type \\ :float) do
%Array{
Expand Down
16 changes: 16 additions & 0 deletions test/array_test.exs
Expand Up @@ -4,6 +4,17 @@ defmodule ArrayTest do
import Matrex.Array
alias Matrex.Array

test "#add sums two arrays of the same shape" do
a = new([1, 2, 3, 4, 5, 6], {3, 2})
b = new([2, 3, 4, 5, 6, 7], {3, 2})

expected = new([3, 5, 7, 9, 11, 13], {3, 2})

c = add(a, b)

assert c == expected
end

test "#inspect shows array in console" do
a = reshape(1..9, {3, 3}, :byte)

Expand All @@ -17,6 +28,11 @@ defmodule ArrayTest do
assert output == expected
end

test "#new creates new array from list" do
a = new([1, 2, 3, 4, 5, 6], {2, 3})
assert at(a, 2, 3) == 6
end

test "#random creates array of random values" do
a = random({10, 25, 25})
assert at(a, {5, 5, 5}) != at(a, {5, 5, 6})
Expand Down

0 comments on commit f0731f8

Please sign in to comment.