Matlab右除法结果疑惑及Python等效实现咨询
/) & Python Equivalents Hey there! Let’s unpack MATLAB’s right division operator and why you might be seeing x * sum(m) ≠ m—plus how to replicate this behavior in Python.
What’s Happening in MATLAB?
First, forget thinking of / as a simple "divide" operation. In MATLAB, A / B is defined as solving the linear equation x * B = A. The result depends on the dimensions and rank of B:
- If
Bis a square, invertible matrix,A/Bis exactlyA * inv(B), andx*Bwill perfectly equalA. - If
Bis non-square (like yoursum(m)being a row vector whenmis a matrix) or singular, MATLAB returns the least-squares solution. This means it finds thexthat minimizes the squared errornorm(x*B - A)—there’s no exact solution tox*B = A, so this is the closest possible fit. That’s why you’re seeingx * sum(m) ≠ m!
Example in MATLAB
Let’s use a concrete matrix to see this:
m = [1 2 3; 4 5 6]; s = sum(m); % s = [5 7 9] (a 1x3 row vector) x = m / s; % x is a 2x1 vector
Calculating x*s gives a 2x3 matrix that’s close to m, but not identical—it’s the best fit possible via least squares.
Replicating This in Python
Python’s NumPy library has tools to match MATLAB’s right division behavior, depending on whether you need an exact or least-squares solution.
1. Least-Squares Solution (For Non-Square/Singular B)
Use numpy.linalg.lstsq to directly solve the least-squares problem. We need to adjust dimensions slightly to match the equation format:
import numpy as np m = np.array([[1, 2, 3], [4, 5, 6]]) s = m.sum(axis=0) # Same as MATLAB's sum(m), gives [5,7,9] # Solve x*s = m → equivalent to s.T * x.T = m.T x_lstsq = np.linalg.lstsq(s.reshape(1, -1), m.T, rcond=None)[0].T
2. Using Pseudoinverse
MATLAB’s right division for non-square cases under the hood uses the Moore-Penrose pseudoinverse. You can replicate this with numpy.linalg.pinv:
x_pinv = m @ np.linalg.pinv(s.reshape(1, -1))
This will give the exact same result as lstsq (and MATLAB’s / operator).
3. Exact Division (When sum(m) is a Scalar)
If m is a vector, sum(m) is a scalar, and MATLAB’s m/sum(m) is just element-wise division. In Python, this is straightforward:
m = np.array([1,2,3]) s = m.sum() x = m / s # x*s will equal m exactly
内容的提问来源于stack exchange,提问作者emma qqq

