Anton Harald
Anton Harald

Reputation: 5924

Clojure / core.matrix / initialize 2d array

In clojure a 2-d array can be initialized with a value like so:

(defn vec2d
  "Return an x by y vector with all entries equal to val."
  [x y val]
  (vec (repeat y (vec (repeat x val)))))

Is there maybe a core.matrix built-in feature that would do the job?

Upvotes: 1

Views: 488

Answers (1)

Sam Estep
Sam Estep

Reputation: 13294

You can use new-matrix and fill:

(require '[clojure.core.matrix :as matrix])

(defn vec2d
  "Return an x by y vector with all entries equal to val."
  [x y val]
  (matrix/fill (matrix/new-matrix y x) val))

If you need the result to be a regular 2D Clojure vector, you can call to-nested-vectors on the result. At that point, though, you're probably better off just using the original solution from your question.

Upvotes: 1

Related Questions