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

Matlab右除法结果疑惑及Python等效实现咨询

Understanding MATLAB's Right Division (/) & 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 B is a square, invertible matrix, A/B is exactly A * inv(B), and x*B will perfectly equal A.
  • If B is non-square (like your sum(m) being a row vector when m is a matrix) or singular, MATLAB returns the least-squares solution. This means it finds the x that minimizes the squared error norm(x*B - A)—there’s no exact solution to x*B = A, so this is the closest possible fit. That’s why you’re seeing x * 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:56:20