python - Matlab sub2ind 到 python
问题描述
row = [1 2 3 1];
col = [2 2 2 3];
sz = [3 3];
ind = sub2ind(sz,row,col)
Result:
ind = 1×4
4 5 6 7
我有以下来自 Matlab 文档的示例。我想在 python 中生成具有相同结果的代码。我在其他帖子中看到了 3-D 数组的情况How to get the linear index for a numpy array (sub2ind) 但我想要一个简单的 2-D 数组的情况,就像我展示的那样。答案代码表示赞赏!
解决方案
def sub2ind(sz, row, col):
n_rows = sz[0]
return [n_rows * (c-1) + r for r, c in zip(row, col)]
首先获取行数。然后每个索引是次(列 - 1)+行。
使用
>>> row = [1, 2, 3, 1];
>>> col = [2, 2, 2, 3];
>>> sz = [3, 3];
>>> sub2ind(sz, row, col)
[4, 5, 6, 7]
推荐阅读
- c# - 异步执行代码并返回 MVC 动作
- reactjs - c# + reactjs + typescript + 基于令牌的身份验证的模板
- php - 使用 Abyss Web Server 实现 MySQL 时如何修复 HY000/2054?
- c# - 角色触墙后无法移动
- javascript - 将参数从我的函数传递到调用函数
- python-3.x - 如何使用 numpy 构建 RNN
- excel - 在 Excel 2016 (Office 365) 中隐藏/显示图表占位符
- python-3.x - 将 Numpy ndarray 连接到 Pandas 数据帧
- c++ - 在结构向量中获取数据作为输入时出现分段错误(SIGSEGV)
- html - CSS自定义下拉列表修改父div高度