【问题标题】:How to convert indexing from Matlab to Python?如何将索引从 Matlab 转换为 Python?
【发布时间】:2021-11-16 15:58:58
【问题描述】:

我正在尝试将此代码从 Matlab 转换为 Python:

index = Output_num - 3;

X = Data(1:end - 3, 1:end);
T = Data(end + index:end + index, 1:end);

我测试了许多选项,但其中任何一个都适合我。

我试过这样:

index = Output_num -3 #this works good

X = Data[0:-3] # I think this works good ( I compared results with the one from Matlab)

T1 = Data[-1] # with this one I try to access to the last row of the 2d array. The aim was to access on it and then add index on all the rows with the following:

T = T1 + index

【问题讨论】:

  • 请提供更多关于您已经尝试过的信息,以便我们更好地帮助您。
  • @TheCodingPenguin 问题已编辑。谢谢

标签: python matlab indexing


【解决方案1】:

我不知道你的初始数据是什么样的,但我从你的回答中假设它是一个二维数组。

对于python中的二维数组:

rows, cols = (10, 10)
Data = [[1]*cols]*rows

要访问此数组,您需要以这种方式同时使用行和列索引:

print(Data[row_number][col_number])

额外的访问和分配:

Data[-1][-1] = 9 #assign constant to the last element of the 2D array
print(Data[0][0]) #print the first element of 2D array
print(Data[-1]) #print the last row of 2D array including the assigned number

输出:

Data[0][0] = 1
Data[-1] = [1, 1, 1, 1, 9]

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 2021-06-03
    • 2017-11-23
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2019-05-11
    • 2016-01-21
    相关资源
    最近更新 更多