How to create a sub-matrix from an array in Python?

Asked

Viewed 1,063 times

1

I managed to generate a matrix via Python and through this generated matrix I had to generate a 3x3 matrix. But I don’t know how to do this, I was researching and I know that Python himself has a resource for this, but I’m not finding.

Example:

I have the Matrix:

Matriz Principal

Upshot

And through this generated Matrix she was going to return me other 3x3 Matrices of this, as in the photo below:

Resultado

If anyone can help me and I’d be extremely grateful!

Thank you!

  • 3

    Welcome to the SOPT. I gave an answer, but I had to have a lot of good will because you didn’t make it easy: instead of posting your matrix information in text, you used an image, which prevents anyone from copying and pasting (I had to type everything, almost did not answer for it). In the future, if you want help, try to make life easier for colleagues, okay? Read [help]. There is information on how to format content in your question. Good luck!

1 answer

4


Simple: use the package Numpy and make slicing. Example:

import numpy as np

matriz = np.array([
            [13, 28, 45, 50, 26, 10],
            [27, 24, 22, 33, 88, 11],
            [90, 25, 85, 23, 76, 55],
            [77, 15, 31, 29, 13, 14],
            [66, 41, 50, 20, 47, 11]
         ])

print(matriz[0:3, 1:4])
print('')
print(matriz[2:, 0:3])

Exit:

[[28 45 50]
 [24 22 33]
 [25 85 23]]

[[90 25 85]
 [77 15 31]
 [66 41 50]]

See working on Ideone.

  • Wow, great tip, Luiz Fernando. But there’s a catch, this problem I’m working on is for my university, and it’s kind of forced to use Pycharm, and Pycharm doesn’t recognize the import of numpy. If it’s not too much trouble, can you tell me if there’s a way for Pycharm to recognize numpy or have some other way to resolve this matrix issue? Thank you very much!

  • Well, you don’t mention anything about Pycharm or the impossibility of using Numpy in your question. If you had mentioned it, I wouldn’t have responded like that. Anyway, that’s another problem, and so I suggest you open up a new question about it. On Soen you already have one that can help you: http://stackoverflow.com/questions/25815567/problems-with-numpy-in-pycharm. In addition to the site mentioned there, you can download Numpy from here (if you use Windows): http://www.lfd.uci.edu/~gohlke/pythonlibs/ Good luck! P.S.: Oh, my name is not Luiz Fernando. :)

  • 1

    Ah, about having another way to solve, of course you do. You process the matrix indexes yourself and extract what you want. Python’s native list also has slicing. It is not facilitated like Numpy’s arrays, but with it and with a loop for you can do.

  • 1

    Understood, Luiz Vieira. I will try to do what you recommended. And sorry for the confusion of the names, I have a thousand rs. Thanks for the help!

  • It was nothing. Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.