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

如何用Python复现MATLAB中基于逻辑数组提取数组元素的代码?

Converting MATLAB's tTacho = tDiff(xDiff == 2) to Python

The MATLAB code you're looking to replicate does two core things: first, it creates a boolean mask marking where elements in xDiff equal 2, then uses that mask to pull the corresponding elements from tDiff into tTacho. Here's how to do this in Python, tailored to whether you're using numpy arrays (the closest match to MATLAB's array workflow) or standard Python lists:

If you’re working with numpy arrays (the standard for numerical operations in Python), the code is nearly identical to MATLAB:

import numpy as np

# Assume xDiff and tDiff are numpy arrays (e.g., created with np.array())
tTacho = tDiff[xDiff == 2]

This works because numpy supports boolean indexing just like MATLAB. The expression xDiff == 2 generates a boolean array matching the shape of xDiff, where each entry is True if the corresponding xDiff element is 2, and False otherwise. Using this mask to index into tDiff extracts only the elements where the mask is True.

Using Standard Python Lists

If you’re working with regular Python lists instead of numpy arrays, a list comprehension will get the job done:

# Assume xDiff and tDiff are standard Python lists
tTacho = [t_val for x_val, t_val in zip(xDiff, tDiff) if x_val == 2]

Breakdown of this code:

  • zip(xDiff, tDiff) pairs up elements from both lists (e.g., (xDiff[0], tDiff[0]), (xDiff[1], tDiff[1]))
  • The comprehension iterates over each pair, checks if x_val equals 2, and adds the corresponding t_val to tTacho if the condition is met.

内容的提问来源于stack exchange,提问作者Steven Goddard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:58:02