Danny
Danny

Reputation: 45

extracting a subarray from an array in python using numpy

if this is given on a homework assignment:

import numpy as np
room_matrix = \
np.array(
[[6,  3, 4, 1],
[5,  2, 3, 2],
[8,  3, 6, 2],
[5,  1, 3, 1],
[10, 4, 7, 2]])

and the task is:

write an expression that retrieves the following submatrix from room_matrix:

array([[2,3],
      [3,6]])

I have done this so far:

a=room_matrix[1,1:3]
b=room_matrix[2,1:3]

then I print "a" and "b" and the output is:

[2 3]
[3 6]

but I want them to be executed as an actual subarray like so:

array([[2,3],
      [3,6]])

Can I concatenate "a" and "b"? Or is there another way to extract a sub array so that the output actually shows it as an array, and not just me printing two splices? I hope this makes sense. Thank you.

Upvotes: 1

Views: 9802

Answers (3)

user7971319
user7971319

Reputation:

The question has already been answered, so just throwing it out there, but, indeed, you could use np.vstack to "concatenate" your a and b matrices to get the desired result:

In [1]: import numpy as np

In [2]: room_matrix = \
...: np.array(
...: [[6,  3, 4, 1],
...: [5,  2, 3, 2],
...: [8,  3, 6, 2],
...: [5,  1, 3, 1],
...: [10, 4, 7, 2]])

In [3]: a=room_matrix[1,1:3]

In [4]: b=room_matrix[2,1:3]

In [5]: np.vstack((a,b))
Out[5]: 
array([[2, 3],
       [3, 6]])

Upvotes: 0

Akavall
Akavall

Reputation: 86356

How about this:

In [1]: import numpy as np

In [2]: room_matrix = \
   ...: np.array(
   ...: [[6,  3, 4, 1],
   ...: [5,  2, 3, 2],
   ...: [8,  3, 6, 2],
   ...: [5,  1, 3, 1],
   ...: [10, 4, 7, 2]])

In [3]: room_matrix
Out[3]: 
array([[ 6,  3,  4,  1],
       [ 5,  2,  3,  2],
       [ 8,  3,  6,  2],
       [ 5,  1,  3,  1],
       [10,  4,  7,  2]])

In [4]: room_matrix[1:3, 1:3]
Out[4]: 
array([[2, 3],
       [3, 6]])

Upvotes: 1

ShreyasG
ShreyasG

Reputation: 806

You needn't do that in two lines. Numpy allows you to splice within a single statement, like this:

room_matrix[1:3, 1:3]
#will slice rows starting from 1 to 2 (row numbers start at 0), likewise for columns

Upvotes: 5

Related Questions