Home > OS >  matlab multidimensional matrix to numpy matrix conversion
matlab multidimensional matrix to numpy matrix conversion

Time:07-21

I want to write this matlab matrix in python : U = [Q S P;S H G;P G E];

where P,Q, S ,H,G, E has a dimension of 103 by 103.

This is what is wrote in pyhton but it's the wrong syntax, U = np.array([[Q ,S, P ],[S, H, G], [P, G, E]]) and gives me wrong dimension

The correct output dimension is 309 by 309

CodePudding user response:

I think you can do multiple concatenations of the arrays with np.concatenate.

Example:

import numpy as np

rows = 103
cols = 103

Q = np.array([[0]*cols]*rows)
S = np.array([[1]*cols]*rows)
P = np.array([[2]*cols]*rows)
H = np.array([[3]*cols]*rows)
G = np.array([[4]*cols]*rows)
E = np.array([[5]*cols]*rows)

U = np.concatenate((np.concatenate((Q,S,P)),np.concatenate((S,H,G)),np.concatenate((P,G,E))), 1)

print("Output dimensions: ", len(U[0]), " by ", len(U))

CodePudding user response:

np.block is closest to what MATLAB does as noted by @MichaelSzczesny in a comment.

import numpy as np

rows = 103
cols = 103

Q = np.ones((rows,cols)) * 1
S = np.ones((rows,cols)) * 2
P = np.ones((rows,cols)) * 3
H = np.ones((rows,cols)) * 4
G = np.ones((rows,cols)) * 5
E = np.ones((rows,cols)) * 6

U = np.block([
    [Q, S, P], 
    [S, H, G],
    [P, G, E]
    ])

print('U has dimensions', U.shape)
# U has dimensions (309, 309)
  • Related