简体   繁体   中英

Get a subarray from a 3d matrix by fixing one axis like in NumPy index+slices

My input is a 3x3x3 array such as this one:

m = [[[0, 1, 2], [3, 4, 5], [6, 7, 8]],
     [[9, 10, 11], [12, 13, 14], [15, 16, 17]],
     [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]

And these are the outputs that I would like to get, using only vectorial or matricial operations:

out1 = [[0,1,2],[3,4,5],[6,7,8]]      (corresponding to indice 0 along first axis)
out2 = [[0,1,2],[9,10,11],[18,19,20]] (corresponding to indice 0 along second axis)
out3 = [[0,3,6],[9,12,15],[18,21,24]] (corresponding to indice 0 along third axis)

I know that I can do that with python using numpy like this:

cube = np.arange(27).resize(3,3,3)
out1 = cube[0,:,:]
out2 = cube[:,0,:]
out3 = cube[:,:,0]

But I need to implement this in javascript. I know how to to do it with loops and indices but I thought there may be a more efficient way to do it.

Using the numjs package that strives to transplant NumPy onto JS (specifically, ndarray.pick from the underlying scijs/ndarray package ):

 var m = nj.array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]); console.log(m.pick(0,null,null));
 <script src="https://cdn.jsdelivr.net/gh/nicolaspanel/numjs@0.15.1/dist/numjs.min.js"></script>

Prints:

"[[0,1,2],[3,4,5],[6,7,8]]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM