sunspots
sunspots

Reputation: 1057

Building up a matrix

I have a function, call it foo, which adds a random number to an input. This process is done twice and collected as a list, i.e.

(defn foo [x] (vec (list (+ x (rand)) (+ x (rand)))))

After collecting the sums into an indexed structure [a b] I'd like to add a random number again to each element (more generally to be able to do multiple arithmetic operations).

(map #(+ % (rand)) [a b])  

Note that the elements a and b are symbolic here, and will be floating points in the real operation.

Now I arrive at my main point of this post and that I would like to repeat the above process 20 times, and output the iterations as a 20x2 matrix. This is where I am stuck in the construction.

Additionally I'd like to loop this process from the beginning, so that rand is added to my input x again giving two new indexed elements [a' b']. Remember that a' and b' are symbolic representations of the floating points, and the primes are used to distinguish the elements from the first loop. Those indexed elements would then be fed back into the mapping and done another 20 times.

This last step I'd like to have as an input parameter in the function, so that I am able to control the number of indexed elements created for the mapping stage (which is done 20 times).

Upvotes: 1

Views: 90

Answers (2)

mikera
mikera

Reputation: 106351

I'd suggest using core.matrix for this kind of array / matrix processing. This is likely to be much easier than manually writing all the array manipulation routines from scratch. See: https://github.com/mikera/core.matrix

There are a number of core.matrix functions that you can use to implement your requirements:

  • emap - applies a function to each element of a multi-dimensional array
  • slices - get a sequence of slices of an array

Upvotes: 1

A. Webb
A. Webb

Reputation: 26446

I would like to repeat the above process 20 times, and output the iterations

Then you are looking for iterate.

I'd like to have as an input parameter in the function, so that I am able to control the number of indexed elements created.

Then you are looking for repeat.

(defn bar [init ncols nrows] 
  (take 
    nrows 
      (iterate
        (partial map + (repeatedly rand)) 
        (repeat ncols init))))

(->> (bar 0 2 20) (mapv vec))

=>; [[0 0]
  ;  [0.1600773061377655 0.25622198504430205]
  ; .
  ; . (20 rows in all) 
  ; .
  ;[3.0414688166175456 4.86821771584174]]

Upvotes: 2

Related Questions