Question

Given two nested vectors x and y, where x is

 (def x [[1 2] [3 4]])

and y is

 (def y [[5 6] [7 8]])

How do I concatenate the nested vectors x and y along array the dimension specified by an additional input d?

Namely, given x, y and d=1 a sample output would be:

[[1 2] [3 4] [5 6] [7 8]]

where y becomes the third and forth rows of the new nested vector.

For d=1 I have tried

(vec (concat [[1 2] [3 4]] [[5 6] [7 8]].

If d=2 with the initial x and y a sample output would be:

[[1 2 5 6] [3 4 7 8]]

This is the case where I am most unsure.

In the case where d=3, x and y would be left alone since they are 2 x 2. So, x and y would be output untouched.

Was it helpful?

Solution

the core.matrix library is excellent for slicing matrices along arbitrary dimensions:

project.clj:

(defproject hello "0.1.0-SNAPSHOT"                                 
  :description "FIXME: write description"                          
  :url "http://example.com/FIXME"                                  
  :license {:name "Eclipse Public License"                         
            :url "http://www.eclipse.org/legal/epl-v10.html"}      
  :dependencies [[org.clojure/clojure "1.5.1"]                     
                 [net.mikera/core.matrix "0.18.0"]]                
  :source-paths ["dev"])                                           

hello/matric.clj:

(ns hello.matrix                                        
  (:refer-clojure :exclude [* - + == /])                
  (:use [clojure.core.matrix]                           
        [clojure.core.matrix.operators]                 
        [clojure.pprint]))                              

(def x (matrix [[1 2] [3 4]]))                          
(def y (matrix [[5 6] [7 8]]))                          
(def xy (matrix [x y]))                                 

(pprint (slices xy 0))                                  
(pprint (slices xy 1))                                  
(pprint (slices xy 2))  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top