1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't new-matrix producing regular nested clojure vectors anyways? I discovered, that the following returns true: (let [mat (m/new-matrix 2 2)] (= (m/to-nested-vectors mat)) mat))
@AntonHarald Yes, but fill does not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.