Skip to content

Instantly share code, notes, and snippets.

@kozo2
Last active February 27, 2016 18:51
Show Gist options
  • Select an option

  • Save kozo2/ea9435d99d9d21fb1312 to your computer and use it in GitHub Desktop.

Select an option

Save kozo2/ea9435d99d9d21fb1312 to your computer and use it in GitHub Desktop.
NArray-devel quickstart tutorial

An example

[1] pry(main)> require "narray"
=> true
[2] pry(main)> a = NArray[0..14].reshape(3, 5)
=> NArray::Int32#shape=[3,5]
[[0, 1, 2, 3, 4],
 [5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14]]
[3] pry(main)> a.shape
=> [3, 5]
[4] pry(main)> a.ndim
=> 2
[5] pry(main)> a.class
=> NArray::Int32
[6] pry(main)> a.size
=> 15

Array Creation

[1] pry(main)> require "narray"
=> true
[2] pry(main)> a = NArray[2,3,4]
=> NArray::Int32#shape=[3]
[2, 3, 4]
[3] pry(main)> a.class
=> NArray::Int32
[4] pry(main)> b = NArray[1.2, 3.5, 5.1]
=> NArray::DFloat#shape=[3]
[1.2, 3.5, 5.1]
[5] pry(main)> b.class
=> NArray::DFloat

NArray transforms sequences of sequences into two-dimensional arrays.

[1] pry(main)> b = NArray[[1.5,2,3], [4,5,6]]
=> NArray::DFloat#shape=[2,3]
[[1.5, 2, 3],
 [4, 5, 6]]
[2] pry(main)> b.class
=> NArray::DFloat

The type of the array can also be explicitly specified at creation time:

[1] pry(main)> c = NArray[[Complex(1), Complex(2)], [Complex(3), Complex(4)]]
=> NArray::DComplex#shape=[2,2]
[[1+0i, 2+0i],
 [3+0i, 4+0i]]

Basic Operations

[1] pry(main)> a = NArray[20,30,40,50]
=> NArray::Int32#shape=[4]
[20, 30, 40, 50]
[2] pry(main)> b = NArray[0..3]
=> NArray::Int32#shape=[4]
[0, 1, 2, 3]
[3] pry(main)> c = a-b
=> NArray::Int32#shape=[4]
[20, 29, 38, 47]
[4] pry(main)> b**2
=> NArray::Int32#shape=[4]
[0, 1, 4, 9]
[5] pry(main)> a<35
=> NArray::Bit#shape=[4]
[1, 1, 0, 0]

Unlike in many matrix languages, the product operator * operates elementwise in NArray.

[1] pry(main)> A = NArray[[1,1], [0,1]]
=> NArray::Int32#shape=[2,2]
[[1, 1],
 [0, 1]]
[2] pry(main)> B = NArray[[2,0], [3,4]]
=> NArray::Int32#shape=[2,2]
[[2, 0],
 [3, 4]]
[3] pry(main)> A*B
=> NArray::Int32#shape=[2,2]
[[2, 0],
 [0, 4]]

Some operations, such as += and *=, act in place to modify an existing array rather than create a new one.

[1] pry(main)> a = NArray[[1,1,1], [1,1,1]]
=> NArray::Int32#shape=[2,3]
[[1, 1, 1],
 [1, 1, 1]]
[2] pry(main)> a *= 3
=> NArray::Int32#shape=[2,3]
[[3, 3, 3],
 [3, 3, 3]]
[3] pry(main)> a
=> NArray::Int32#shape=[2,3]
[[3, 3, 3],
 [3, 3, 3]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment