4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

clojure.core.matrixのお試しサンプル

Posted at

project.cljに以下を追加して

[net.mikera/core.matrix "0.32.1"]

試してみる

sample.clj
(ns matrix.sample
  (:require [clojure.core.matrix :as m]
            [clojure.core.matrix.operators :as o]))

(m/identity-matrix 3)

(o/+ [1 2] [3 4])
(o/* [1 2] 8)

(o/** [[2 3] [4 5]] [2 3])
結果
[[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]]
[4 6]
[8 16]
[[4.0 27.0] [16.0 125.0]]

Rみたいに要素同士での足し算掛け算できた。

sample.clj
(def a [[1 2] [3 4]])
(def b [[1 0] [0 2]])
(o/* a b)
(m/mmul a b)
結果
[[1 0] [0 8]]
[[1 4] [3 8]]

*だと要素同士、mmulだと行列の掛け算になった。

sample.clj
(def c [[:a "ABC" 2] [:b "XYZ" 4] [:c nil 7]])
(m/select c 1)
(m/select c 2 2)
(m/select c :all 1)
(m/select c :all [1 2])
結果
[:b "XYZ" 4]
7
["ABC" "XYZ" nil]
# <NDWrapper [["ABC" 2] ["XYZ" 4] [nil 7]]>

selectで行や列をとってこれた。:all指定すると全行や全列になる。

sample.clj
(def d (m/diagonal-matrix [1 2]))
(def e (m/broadcast [1 5 7] [3 3]))
d
e

(m/sqrt d)
(m/esum d)
(m/emax e)
(m/emap #(* 2 %) e)
結果
[[1 0.0] [0.0 2]]
[[1 5 7] [1 5 7] [1 5 7]]

[[1.0 0.0] [0.0 1.4142135623730951]]
3.0
7
[[2 10 14] [2 10 14] [2 10 14]]

broadcastで同じ行が複数ある行列が作れた。
あとは大体予想通りだけど、特定の行や特定の列だけに演算できるmapとか特定の行だけ取り出すfilterはないんだろうか?
clojure.core.matrix.select/selとか使ってもできなそうだし・・・

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?