4D Matrix operation in Python – conversion from MATLAB
Question:
I’m trying to translate this MATLAB code to Python:
MATLAB: V_c = delta* max(V_L, repmat(V_A_c,[N_p 1]) - NM )
where these are 4D arrays:
V_c
is the continuation value for in different states, (should have shape 81, 75, 15, 31)
V_L
is the initial value, (has shapes 81, 75, 15, 31)
V_A_c
is the value of adjustment under optimal choice (has shape 1, 75, 15, 31)
NM
is a number (NM = κ*np.exp(P0)
)
N_p
is the length of the grid
This is my attempted python code
PYTHON: V_c = delta * np.amax(V_L,(np.tile(V_A_c,(([N_p,1]))))-NM)
I get errors, that the lengths of the arrays are different, and that only integer scalar arrays can be converted to a scalar index.
In Python, my V_L
and V_A_c
has the same values and shapes as the MATLAB gives, but I still can’t compute V_c. Any suggestions?
Answers:
You can’t. You must write it. Even you use converter, you will not reach the exact code. So, try to understand the code and write in python.
The error you mention, comes from the fact that you want to element-wise compare two tensor (matrix). use np.maximum.
considering the tile operation is correct and N_p is 85 in you example:
V_c = delta * np.maximum(V_L, np.tile(V_A_c,(N_p,1,1,1)) - NM )
I’m trying to translate this MATLAB code to Python:
MATLAB: V_c = delta* max(V_L, repmat(V_A_c,[N_p 1]) - NM )
where these are 4D arrays:
V_c
is the continuation value for in different states, (should have shape 81, 75, 15, 31)
V_L
is the initial value, (has shapes 81, 75, 15, 31)
V_A_c
is the value of adjustment under optimal choice (has shape 1, 75, 15, 31)
NM
is a number (NM = κ*np.exp(P0)
)
N_p
is the length of the grid
This is my attempted python code
PYTHON: V_c = delta * np.amax(V_L,(np.tile(V_A_c,(([N_p,1]))))-NM)
I get errors, that the lengths of the arrays are different, and that only integer scalar arrays can be converted to a scalar index.
In Python, my V_L
and V_A_c
has the same values and shapes as the MATLAB gives, but I still can’t compute V_c. Any suggestions?
You can’t. You must write it. Even you use converter, you will not reach the exact code. So, try to understand the code and write in python.
The error you mention, comes from the fact that you want to element-wise compare two tensor (matrix). use np.maximum.
considering the tile operation is correct and N_p is 85 in you example:
V_c = delta * np.maximum(V_L, np.tile(V_A_c,(N_p,1,1,1)) - NM )