Omega001
Omega001

Reputation: 3

Multiplying an array by a number

I've been writing out a function in Clojure that would take a row of a 2d array and then multiples the values in it by a single value. I have the index to get the specific row and the value to multiply the row with in another array.

The function will return the array, that has now got values multipled by the single value.

Here's the code:

(def twod-array [[3.1 0.0023  0.35]
                [0.21 0.00353 8.13]])

(def iandv [1 3.1])

(defn array-multiply [iandv twod-array]
(
      let [array-row (nth twod-array (nth iandv 0))]
      (map * [array-row] [(nth iandv 1)])
)

The let gets the array row and then it will return the row with the values inside multiplied with the value of the "index and value" array.

This has the closest I've gotten using the examples with the clojure.doc website and I'm getting a ClassCastException of the following:

ClassCastException clojure.lang.PersistentVector cannot be cast to java.lang.Number  clojure.lang.Numbers.multiply (Numbers.java:148)

I've been looking at map vector and other map functions but I haven't been able to find a good solution.

Upvotes: 0

Views: 447

Answers (2)

leetwinski
leetwinski

Reputation: 17859

more clojurish way could look something like this:

(defn array-multiply [[row mul] twod-array]
  (update twod-array row #(mapv (partial * mul) %)))

user> (array-multiply iandv twod-array)
;;=> [[3.1 0.0023 0.35] [0.651 0.010943000000000001 25.203000000000003]]

Upvotes: 3

slipset
slipset

Reputation: 3078

Your code is somewhat hard to read, but basically, you're trying to multiply a number and a vector, that doesn't work.

(defn array-multiply [iandv twod-array]
  (let [array-row (nth twod-array (nth iandv 0))]
    (map * array-row [(nth iandv 1)])))

works since array-row already is a vector.

Upvotes: 0

Related Questions