rlunde
rlunde

Reputation: 73

Adding a 2D Array to a 3D Array

Im struggling a little with stacking two matrices on top of each other. I'm using the pyKalman package, which when updated, returns a tuple of matrices. One with an updated estimate (new_pred a 1 x 2 vector) and the corresponding covariance matrix (new_cov a 2 x 2 matrix).

After the update, I want to stack the returned values to their corresponding outputs, for a recursive smoothing of the data, through these estimates.

The following is how it is currently implemented.

for meas in onlineObservations:
    (new_pred, new_cov) = kf.filter_update(states_pred[-1], cov_pred[-1], meas)
    states_pred = np.vstack((states_pred, new_pred))
    cov_pred = np.stack((cov_pred, new_cov), axis=0)

Which works really well for the updated estimate (the 1x2 vector), but fails when i try to add new_cov to the array called cov_pred. For good measure:

states_pred.shape = (900,2)
cov_pred.shape = (900, 2, 2)

I've tried changing the axis of "stack" to no avail. It's probably something elementary, but i've been struggling with it for the past hour, and cannot seem to find a "simple" solution.

Thanks in advance.

Upvotes: 1

Views: 163

Answers (3)

alaa saeed
alaa saeed

Reputation: 1

You can keep your code inside a For Loop (While Loop will also do) and use 'Auto-index Enabled' and thats it.... At the output of Loop, LabVIEW will create a 3D data exactly as your requirement.

Upvotes: 0

Aritesh
Aritesh

Reputation: 2103

This should work -

cov_pred = []
for meas in onlineObservations:
    (new_pred, new_cov) = kf.filter_update(states_pred[-1], cov_pred[-1], meas)
    states_pred = np.vstack((states_pred, new_pred))
    cov_pred.append[new_cov]
cov_pred = np.stack(cov_pred, axis=0)

But since you want to update array which you are using already in code, you should use np.concatenate

for meas in onlineObservations:
    (new_pred, new_cov) = kf.filter_update(states_pred[-1], cov_pred[-1], meas)
    states_pred = np.vstack((states_pred, new_pred))
    cov_pred = np.concatenate((cov_pred, np.reshape(new_cov, (1,2,2))), axis=0)

Upvotes: 2

rlunde
rlunde

Reputation: 73

I've been able to make it work by converting cov_pred to a list, and then use:

cov_pred.append(new_cov)

And then re-convert it back again after the for loop. But it seems tedious - at least if there's an even better way!

Upvotes: 0

Related Questions