You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复错误:func返回的数组必须为一维,但得到ndim=2

Fixing "The array return by func must be one-dimensional, but got ndim=2" in scipy.integrate.odeint

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:56:58