Skip to content

Commit

Permalink
Create matrix from list of matrices
Browse files Browse the repository at this point in the history
  • Loading branch information
versilov committed May 22, 2018
1 parent 5e49491 commit 3e77dc7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
35 changes: 34 additions & 1 deletion lib/matrex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1804,6 +1804,8 @@ defmodule Matrex do
@doc """
Creates new matrix from list of lists or text representation (compatible with MathLab/Octave).
List of lists can contain other matrices, which are concatenated in one.
## Example
iex> Matrex.new([[1, 2, 3], [4, 5, 6]])
Expand All @@ -1813,6 +1815,15 @@ defmodule Matrex do
│ 4.0 5.0 6.0 │
└ ┘
iex> Matrex.new([[Matrex.fill(2, 1), Matrex.fill(2, 3, 2)],
...> [Matrex.fill(1, 2, 3), Matrex.fill(1, 3, 4)]])
#Matrex[5×5]
┌ ┐
│ 1.0 1.0 2.0 2.0 2.0 │
│ 1.0 1.0 2.0 2.0 2.0 │
│ 3.0 3.0 4.0 4.0 4.0 │
└ ┘
iex> Matrex.new("1;0;1;0;1")
#Matrex[5×1]
┌ ┐
Expand Down Expand Up @@ -1840,7 +1851,29 @@ defmodule Matrex do
└ ┘
"""
@spec new([[element]] | binary) :: matrex
@spec new([[element]] | [[matrex]] | binary) :: matrex
def new(
[
[
%Matrex{
data: <<
rows::unsigned-integer-little-32,
columns::unsigned-integer-little-32,
_rest::binary
>>
}
| _
]
| _
] = lol_of_ma
) do
lol_of_ma
|> Enum.map(fn list_of_ma ->
Enum.reduce(list_of_ma, &Matrex.concat(&2, &1))
end)
|> Enum.reduce(&Matrex.concat(&2, &1, :rows))
end

def new([first_list | _] = lol_or_binary) when is_list(first_list) do
rows = length(lol_or_binary)
columns = length(first_list)
Expand Down
14 changes: 13 additions & 1 deletion test/creation_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ defmodule CreationTest do
assert Matrex.new(rows, columns, function) == expected
end

test "#new creates a new matrix initialized by a list" do
test "#new creates a new matrix initialized by a list of lists" do
list = [[1, 2, 3], [4, 5, 6]]

expected = %Matrex{
Expand Down Expand Up @@ -200,6 +200,18 @@ defmodule CreationTest do
assert Matrex.new(list) == expected
end

test "#new creates a new matrix from a list of lists of matrices" do
m1 = Matrex.reshape(1..6, 2, 3)
m2 = Matrex.reshape(7..12, 2, 3)
m3 = Matrex.reshape(13..16, 2, 2)
m4 = Matrex.reshape(17..20, 2, 2)

expected =
Matrex.new([[1, 2, 3, 13, 14], [4, 5, 6, 15, 16], [7, 8, 9, 17, 18], [10, 11, 12, 19, 20]])

assert Matrex.new([[m1, m3], [m2, m4]]) == expected
end

test "#ones creates matrix filled with ones" do
ones_matrix = Matrex.ones(7)

Expand Down

0 comments on commit 3e77dc7

Please sign in to comment.