如何将以下Matlab循环转换为Python?

时间:2016-08-26 04:37:44

标签: python matlab python-2.7

我一直在努力将Matlab代码翻译成Python,并且遇到了一个我很难转换的循环,因为我对这两种语言都很新。

if fdp >=2
degreeTwoVector=[];
counter =1;
for i = 1:numVariables
    for j = 1:numVariables
        degreeTwoVector(counter,:) = [i j 0];
        counter = counter +1;
    end
end

sortedDegreeTwoVector = sort(degreeTwoVector,2);
degreeTwoVector = unique(sortedDegreeTwoVector, 'rows');

combinationVector = [combinationVector; degreeTwoVector];
end

这是我将其转换为python(不完整)时可以想到的:

if fdp >= 2:
    degreeTwoVector = np.array([])
    counter = 1
    for i in range(1, numVariables+1):
        for j in range(1, numVariables+1):
        degreeTwoVector(counter, :) = np.array([i, j, 0])
        counter = counter + 1
        break
    sortedDegreeTwoVector = degreeTwoVector[np.argsort(degreeTwoVector[:, 1])]

我当然知道它有一些错误。如果您能帮助我完成转换并纠正任何错误,我将不胜感激。提前谢谢!

1 个答案:

答案 0 :(得分:3)

你离我太远了: 你不需要一个break语句,它会导致一个早熟的,中断,循环(在第一次迭代)。 所以你走了:

numVariables = np.shape(X)[0] #  number of rows in X which is given
if fdp >= 2:
    degreeTwoVector = np.zeros((numVariables, 3)) #  you need to initialize the shape
    counter = 0 # first index is 0
    for i in range(numVariables):
        for j in range(numVariables):
            degreeTwoVector[counter, :] = np.array([i, j, 0])
            counter = counter + 1 #  counter += 1 is more pythonic
    sortedDegreeTwoVector = np.sort(degreeTwoVector, axis=1);
    degreeTwoVector = np.vstack({tuple(row) for row in sortedDegreeTwoVector})

    combinationVector = np.vstack((combinationVector, degreeTwoVector))

编辑:在原始问题中添加了等效的循环代码。

除了我没有看到你定义combinationVector的位置这一事实外,一切都应该没问题。