首页 > 解决方案 > 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 数组的情况,就像我展示的那样。答案代码表示赞赏!

标签: pythonarraysmatlab

解决方案


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]

推荐阅读