NumPy矩阵与标量表达式不匹配:离散时间系统仿真输出不一致求助
I'm working on porting a discrete-time system simulation to embedded C, and I've hit a frustrating roadblock: when I convert the original matrix-based equations into equivalent scalar expressions, the output doesn't match the results from the matrix implementation. Since embedded C can't natively handle matrix operations, I need to get this scalar conversion right to move forward with the project.
Context
- The original system uses matrix operations (like state updates such as
x(k+1) = A*x(k) + B*u(k)) which produce fully validated, correct outputs. - I've expanded these matrix equations into individual scalar calculations to fit the constraints of embedded C code.
- When running the exact same input parameters through both implementations, the scalar version's output diverges from the matrix-based baseline.
What I Need Help With
I need to run a test using the specified input parameters, then compare the screenshot of the matrix implementation's correct output against the scalar implementation's output to pinpoint where the mismatch is happening.
Potential Areas I’ve Checked (But Might Have Missed)
- Index Mismatches: Double-checking that matrix row/column indices map correctly to scalar variables (e.g., ensuring
A[0][1]in the matrix is indeed the coefficient multiplyingx2in the first scalar state equation). - Operation Order: Verifying that the order of additions and multiplications matches the implicit order of the matrix operation (no accidental reversal of terms that could throw off results).
- Initial Conditions: Confirming that initial state values are identical across both implementations—no overlooked initializations in the scalar code.
Example Snippet For Reference
Original matrix operation (Python/Numpy, correct output):
import numpy as np # System matrices A = np.array([[0.9, 0.1], [0.05, 0.95]]) B = np.array([[0.5], [0.2]]) # Initial state and input x_k = np.array([1.0, 0.0]) u_k = 2.0 # State update x_k1 = A @ x_k + B @ u_k
Converted scalar implementation (C,待验证输出):
float A11 = 0.9f, A12 = 0.1f; float A21 = 0.05f, A22 = 0.95f; float B1 = 0.5f, B2 = 0.2f; float x1 = 1.0f, x2 = 0.0f; float u = 2.0f; float x1_next = A11 * x1 + A12 * x2 + B1 * u; float x2_next = A21 * x1 + A22 * x2 + B2 * u;
If anyone can help walk through comparing the outputs from these two implementations (using the given parameters) and spot where the scalar conversion might be going wrong, I'd really appreciate it.
内容的提问来源于stack exchange,提问作者dash-dot

