ymmx
ymmx

Reputation: 4967

Is it possible to put a 1D ndarray (size N) into 1D ndarray (size N,1)

I'm trying to put results of a calculus into a big matrix where the last dimension can be 1 or 2 or more. so to put my result in the matrix I do

res[i,j,:,:] = y

If y is sized (N,2) or more than 2 it is find, but if y is sized (N) I got an error saying:

ValueError: could not broadcast input array from shape (10241) into shape (10241,1)

Small example:

import numpy as np

N=10
y = np.zeros((N,2))
res = np.zeros((2,2,N,2))
res[0,0,:,:]= y

y = np.zeros((N,1))
res = np.zeros((2,2,N,1))
res[0,0,:,:]= y

y = np.zeros(N)
res = np.zeros((2,2,N,1))
res[0,0,:,:]= y

I'm getting the error for the last example but they are both (y and res) 1D vector right?

I'm wondering if it exists a solution to make this assignment whatever the size of the last dimension (1, 2 or more)?

In my code I made an try except but could exist another way

try:
    self.res[i,j,:,:] = self.ODE_solver(len(self.t))
except:
    self.res[i, j, :, 0] = self.ODE_solver(len(self.t))

Upvotes: 0

Views: 62

Answers (2)

James
James

Reputation: 36598

You can reshape y to be the last 2 dimensions of res.

N=10
y = np.zeros((N,2))
res = np.zeros((2,2,N,2))
res[0,0,:,:]= y.reshape(res.shape[-2:])

y = np.zeros((N,1))
res = np.zeros((2,2,N,1))
res[0,0,:,:]= y.reshape(res.shape[-2:])

y = np.zeros(N)
res = np.zeros((2,2,N,1))
res[0,0,:,:]= y.reshape(res.shape[-2:])

Upvotes: 1

Divakar
Divakar

Reputation: 221514

For the generic solution that works across all three scenarios, use -

res[0,0,:,:] = y.reshape(y.shape[0],-1)

So, basically, we are making y 2D while keeping the first axis length intact and changing the second one based on the leftover.

Upvotes: 1

Related Questions