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

Matlab转Julia:求数组最小元素所在行索引的等效实现

Julia Equivalent for Your MATLAB Code

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 (while min() is for scalar pairs).
  • dims=2 in Julia is equivalent to [],2 in MATLAB for row-wise calculations.
  • vec() converts the 2D column matrix from minimum(; dims=2) into a 1D vector, ensuring findmin() returns the correct row index.

内容的提问来源于stack exchange,提问作者Ryan Lockwood

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:05:40