【问题标题】:What does find(x==1) in MATLAB exactly return and what is equivalent to it in python?MATLAB 中的 find(x==1) 究竟返回什么,python 中的等价物是什么?
【发布时间】:2021-08-02 22:06:01
【问题描述】:

我正在尝试执行以下 MATLAB 代码在 python 中所做的事情,但我不太理解它的输出。这是MATLAB代码

A = zeros((48,60));

A(3,5) = 1;
A(3,6) = 1;
A(48,60) = 1;
A(47,60) = 1;
A(24,30) = 1;
A(38,45) = 1;

f = find(A == 1);

最后一行f 返回[195;243;1416;2150;2879;2880],这是一列数字。但我不明白这些数字是如何从 find() 获得的。似乎它没有将行号和列号相乘。为什么我得到这些数字?另外,我应该怎么做才能在 python 中得到同样的东西?

A= np.zeros(48, 60)
A[2, 4] = 1
A[2, 5] = 1
A[47, 59] = 1
A[46, 59] = 1
A[23, 29] = 1
A[37, 44] = 1

np.where(A ==1)

我试过np.where(A== 1),但它只返回行和列的索引。

【问题讨论】:

    标签: python arrays numpy matlab find


    【解决方案1】:

    matlab 中的 find 命令返回每个元素的线性索引。更多可以在这里找到:https://www.mathworks.com/help/matlab/ref/find.html#budquyz-1

    等效的 Python 代码将是 np.argwhere,它也返回索引:https://numpy.org/doc/stable/reference/generated/numpy.argwhere.html

    要获得与 matlab 完全相同的行为,您必须将矩阵转换为向量:

    A= np.zeros((48, 60))
    A[2, 4] = 1
    A[2, 5] = 1
    A[47, 59] = 1
    A[46, 59] = 1
    A[23, 29] = 1
    A[37, 44] = 1
    
    np.argwhere(np.ravel(A)==1)
    

    【讨论】:

    • 我实际上也尝试过np.argwhere(A==1),但它只是返回 (array([ 2, 2, 23, 37, 46, 47], dtype=int64), array([ 4, 5, 29, 44, 59, 59], dtype=int64)) 有没有办法像 MATLAB 一样获得相同的线性索引?
    猜你喜欢
    • 1970-01-01
    • 2011-01-09
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多