I am having a small script in numpy (Ubuntu 18.04, Python 3.6.9, numpy 1.18.3). I want to squeeze an array, but I somehow do not manage to do it.
Looking at numpy documentation, np.squeeze should be able to do that. So I did the following:
print(self.U.shape)
print(self.renorm_action)
to_plot = np.squeeze(self.U) / self.renorm_action
print(to_plot.shape)
It prints:
(1, 1002)
1.0
(1, 1002)
I am very surprised, as I would expect:
(1, 1002)
1.0
(1002,)
instead. Any idea what I am doing wrong?
Explanation
Thanks for the great help in comments, and looking forward to the 'answer', but shortly, looks like lqr returns a matrix, which is always 2D. This may be inconsistent with the doc of the control package.
Edits
Edit 1
I really do not understand why this does not work. In python3 terminal I am well able to do:
$ python3
Python 3.6.9 (default, Apr 18 2020, 01:56:04)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> arr = np.zeros((1, 1002))
>>> arr.shape
(1, 1002)
>>> arr2 = np.squeeze(arr)
>>> arr2.shape
(1002,)
Edit 2
Of course I can find a workaround, i.e. this works, but this is ugly...
print(self.U.shape)
print(self.renorm_action)
to_plot = np.zeros((self.total_nbr_timesteps,))
to_plot[:] = np.squeeze(self.U)[0, :] / self.renorm_action
print(to_plot.shape)
prints:
(1, 1002)
1.0
(1002,)
There is really something I do not understand / miss here... :(
Edit 3
So this is (of course...) part of a quite large program. But here is a short snippet I can write to reproduce the problem. If this is min_ex.py
:
import numpy as np
import control
total_nbr_timesteps = 5
A = np.array([[0, 0, 1, 0],
[0, 0, 0, 1],
[-418, 0, -0.184, 0],
[0, -16343, 0, -0.767]])
B = np.array([[0],
[0],
[0.0002],
[-0.0034]])
nbr_modes = A.shape[1]
X = np.zeros((nbr_modes, total_nbr_timesteps))
Q = np.eye(nbr_modes)
R = np.array([1.0])
N = np.array([[0.0],
[0.0],
[0.0],
[0.0]])
K_lqr, _, _ = control.lqr(A, B, Q, R, N)
# K_lqr = np.ones((1, 4)) # using this matrix instead, it works
print(K_lqr.shape)
print(X.shape)
U = -K_lqr @ X
print(U.shape)
to_plot = np.squeeze(U)
print(to_plot.shape)
# this prints:
# $ python3 min_ex.py
# (1, 4)
# (4, 5)
# (1, 5)
# (1, 5)