Matlab自定义mynorm函数转Python:适配多输入场景的实现问询
Got it, let's break this down clearly since the mynorm implementation you found doesn't match how it's being called in your original MATLAB code!
What Your Actual mynorm Function Does
The mynorm.m you found is a simple version for two scalar inputs, but your MATLAB calls tell a different story:
mynorm(fea2, 1): Calculates the L2 norm of each column in thefea2matrix (MATLAB'sdim=1refers to column-wise operations)mynorm(iris(:,1:4),2): Calculates the L2 norm of each row in the first 4 columns ofiris(MATLAB'sdim=2refers to row-wise operations)
This means your real mynorm is a function that computes L2 norms along a specified dimension of a matrix, not just for two scalars.
Python Equivalent Implementations (Using NumPy)
NumPy has all the tools we need to replicate this behavior—here are two ways to do it:
1. Use NumPy's Built-in norm Function Directly
You can map MATLAB's dimension parameter directly to NumPy's axis parameter (note: MATLAB uses 1-based indexing, NumPy uses 0-based):
- For your first call
feaNorm = mynorm(fea2, 1):import numpy as np feaNorm = np.linalg.norm(fea2, axis=0) # axis=0 = column-wise, matches MATLAB dim=1 - For your second call
feaNorm = mynorm(iris(:,1:4),2):# Remember Python uses 0-based indexing, so first 4 columns are indices 0-3 iris_subset = iris[:, 0:4] feaNorm = np.linalg.norm(iris_subset, axis=1) # axis=1 = row-wise, matches MATLAB dim=2
2. Wrap It in a Custom mynorm Function
If you want to keep the exact function name and call syntax from MATLAB, wrap the NumPy logic:
import numpy as np def mynorm(x, dim): # Convert MATLAB's 1-based dimension to NumPy's 0-based axis axis = dim - 1 return np.linalg.norm(x, axis=axis)
Now you can call it exactly like in MATLAB:
feaNorm = mynorm(fea2, 1) feaNorm = mynorm(iris[:, 0:4], 2)
3. Manual Implementation (No np.linalg.norm)
If you want to replicate the sqrt(dot(v,v)) logic from the comment in your found mynorm.m (extended to matrices), here's how:
import numpy as np def mynorm(x, dim): axis = dim - 1 # Square all elements, sum along the target axis, then take square root return np.sqrt(np.sum(x ** 2, axis=axis))
All these implementations will behave exactly like the mynorm in your original MATLAB code.
内容的提问来源于stack exchange,提问作者Pallavi

