Matlab转Julia:求数组最小元素所在行索引的等效实现
Let's break down how to replicate that MATLAB logic in Julia step by step, then put it all together into a clean one-liner.
Step 1: Compute row-wise minima
In MATLAB, min(M,[],2) calculates the minimum value for each row and returns a column vector. In Julia, you can replicate this with minimum(M; dims=2). Note that this returns a 2D matrix (not a 1D vector), so we’ll need to flatten it later to get the correct index.
Using your sample matrix as an example:
M = [1 1 1; 1 1 0; 1 1 1] row_minima = minimum(M; dims=2) # Output: # 3×1 Matrix{Int64}: # 1 # 0 # 1
Step 2: Find the index of the smallest row minimum
MATLAB’s [~, row] = min(row_minima) gives you the row index of the smallest value. In Julia, findmin() returns a tuple of (minimum_value, linear_index). By flattening the 2D row minima result to a 1D vector, the linear index directly maps to the row number we need.
First, flatten the 2D result with vec():
flat_row_minima = vec(row_minima) min_val, pStar = findmin(flat_row_minima) # pStar will be 2, matching your MATLAB example
Combined One-Liner
Putting it all together (matching your original MATLAB code that combines dPlus and dMinus):
_, pStar = findmin(vec(minimum([dPlus dMinus]; dims=2)))
Key Notes
- Julia uses
minimum()for array-wise minimum operations (whilemin()is for scalar pairs). dims=2in Julia is equivalent to[],2in MATLAB for row-wise calculations.vec()converts the 2D column matrix fromminimum(; dims=2)into a 1D vector, ensuringfindmin()returns the correct row index.
内容的提问来源于stack exchange,提问作者Ryan Lockwood

