1

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.

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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]])

1 Comment

That works. Thank you! Not sure why I didn't realize it to be that simple.
0

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]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.