如何修复错误:func返回的数组必须为一维,但得到ndim=2
Hey there, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
The main issue here is the order of arguments in your g function doesn't match what odeint expects.
scipy.integrate.odeint requires the callback function to follow this signature:
def func(y, t, *args): # compute dy/dt here return dy_dt
But your function is defined as def g(t,y,B): — you swapped the t and y parameters!
When odeint calls your function, it passes the current state y first, then the time t. Since you have them reversed, your code is treating the scalar t as the state vector y, and then doing np.dot(t, B). A scalar multiplied by a 5x5 matrix gives another 5x5 matrix (2-dimensional), which odeint can't handle — hence the error about returning a 2D array instead of 1D.
The Fix
Just swap the order of t and y in your g function definition. Also, let's double-check that the return value is indeed a 1D array (which it will be once the parameters are correct):
import numpy as np from scipy.integrate import odeint y0 = np.array([1,3,2,3,5]) b = np.array([[1],[3],[4],[2],[5]]) B = np.dot(b, b.T) # Fixed parameter order: y comes first, then t def g(y, t, B): # y is a 1D array, B is 5x5 — np.dot(y, B) gives a 1D array of shape (5,) return np.exp(np.dot(y, B)) t = np.linspace(0, 1, 100) y = odeint(g, y0, t, args=(B,))
Why This Works
Now when odeint calls g, it passes the 1D state vector y first. np.dot(y, B) computes a 1D array (shape (5,)), and np.exp preserves that 1D shape — exactly what odeint expects for the derivative of your state vector.
内容的提问来源于stack exchange,提问作者Lucas

