What is the best way to translate the generation of a multidimensional cell array from Matlab to Clojure -
i'm halfway through figuring out solution question, have feeling won't efficient. i've got 2 dimensional cell structure of variable length arrays constructed in non-functional way in matlab convert clojure. here example of i'm trying do:
pre = cell(n,1); aux = cell(n,1); i=1:ne j=1:d k=1:length(delays{i,j}) pre{post(i, delays{i, j}(k))}(end+1) = n*(delays{i, j}(k)-1)+i; aux{post(i, delays{i, j}(k))}(end+1) = n*(d-1-j)+i; % takes account delay end; end; end;
my current plan implementation use 3 loops first initialized vector of n vectors of empty vector. each subloop initialized previous loop. define separate function takes overall vector , subindices , value , returns vector updated subvector.
there's got smarter way of doing using 3 loop/recurs. possibly reduce function simplifies syntax using accumulator.
i'm not 100% sure understand code doing (i don't know matlab) might 1 approach building multi-dimensional vector:
(defn conj-in "based on clojure.core/assoc-in, vectors instead of maps." [coll [k & ks] v] (if ks (assoc coll k (conj-in (get coll k []) ks v)) (assoc coll k v))) (defn foo [] (let [w 5, h 4, d 3 indices (for [i (range w) j (range h) k (range d)] [i j k])] (reduce (fn [acc [i j k :as index]] (conj-in acc index ;; real work here (str j k))) [] indices))) user> (pprint (foo)) [[["000" "001" "002"] ["010" "011" "012"] ["020" "021" "022"] ["030" "031" "032"]] [["100" "101" "102"] ["110" "111" "112"] ["120" "121" "122"] ["130" "131" "132"]] [["200" "201" "202"] ["210" "211" "212"] ["220" "221" "222"] ["230" "231" "232"]] [["300" "301" "302"] ["310" "311" "312"] ["320" "321" "322"] ["330" "331" "332"]] [["400" "401" "402"] ["410" "411" "412"] ["420" "421" "422"] ["430" "431" "432"]]]
this works if indices
go in proper order (increasing), because can't conj
or assoc
onto vector anywhere other one-past-the-end.
i think acceptable use make-array
, build array via aset
. why clojure offers access java mutable arrays; algorithms more elegant way, , need them performance. can dump data clojure vectors after you're done if want avoid leaking side-effects.
(i don't know of or other version performs better.)
(defn bar [] (let [w 5, h 4, d 3 arr (make-array string w h d)] (doseq [i (range w) j (range h) k (range d)] (aset arr j k (str j k))) (vec (map #(vec (map vec %)) arr)))) ;yikes?
Comments
Post a Comment