3

I want to make a 2x2 matrix

T = [[A, B],
     [C, D]]

where each element A,B,C,D is an array (of same size, of course). Is this possible?

I would like to be able to multiply these matrix, for example multiplying two matrix T1 and T2 should give me

T1*T2 = [[A1*A2, B1*B2],
         [C1*C2, D1*D2]]

which is still a matrix of arrays of the same size. Is there such a multiplication function?

And also, if I multiply T with a normal scalar matrix t = [[a,b],[c,d]] where a,b,c,d are scalar numbers, the the multiplication should give me

t*T = [[a*A, b*B],
       [c*C, d*D]]

How can I do this? An example or a link to related material would be great.

2 Answers 2

2

Doesn't your first question just work as you would expect?

In [1]: import numpy as np

In [2]: arr = np.arange(8).reshape(2, 2, 2)

In [3]: arr
Out[3]: 
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

In [4]: arr*arr
Out[4]: 
array([[[ 0,  1],
        [ 4,  9]],

       [[16, 25],
        [36, 49]]])

As for your second question, just reshape it to a 3 dimensional array:

In [5]: arr2 = np.arange(4).reshape(2, 2)

In [6]: arr2
Out[6]: 
array([[0, 1],
       [2, 3]])

In [7]: arr2 = arr2.reshape(2, 2, 1)

In [8]: arr2
Out[8]: 
array([[[0],
        [1]],

       [[2],
        [3]]])

In [9]: arr*arr2
Out[9]: 
array([[[ 0,  0],
        [ 2,  3]],

       [[ 8, 10],
        [18, 21]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is awesome. I think my mistake to the first part is that I should use array function to construct the matrix, not the matrix function. Second part works perfectly, exactly what I want.
0
>>> from numpy import array, matrix, multiply
>>> A = array([1, 2, 3])
>>> 
>>> B = array([2, 3, 4])
>>> 
>>> C = array([4, 5, 6])
>>> 
>>> D = array([7, 8, 9])
>>> 
>>> T1 = matrix([A, B, C, D])
>>> T1
matrix([[1, 2, 3],
        [2, 3, 4],
        [4, 5, 6],
        [7, 8, 9]])
>>> T2 = T1 * 100
>>> T2
matrix([[100, 200, 300],
        [200, 300, 400],
        [400, 500, 600],
        [700, 800, 900]])
>>> 
>>> multiply(T1, T2)
matrix([[ 100,  400,  900],
        [ 400,  900, 1600],
        [1600, 2500, 3600],
        [4900, 6400, 8100]])
>>> 

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.