简体   繁体   English

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

[英]How to convert the following Matlab loop into Python?

I have been working on translating Matlab code into Python and came across a loop that I'm having some difficulty converting as I'm fairly new to both the languages. 我一直在努力将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

Here's what I could come up with while converting it to python(incomplete): 这是将其转换为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])]

I certainly know there are some mistakes in it. 我当然知道其中有一些错误。 So I'd be grateful if you could help me complete the conversion and correct any mistakes. 因此,如果您能帮助我完成转换并纠正任何错误,我们将不胜感激。 Thanks in advance! 提前致谢!

You are not too far off: You do not need a break statement, it is causing a precocious, well, break to the loop (at the first iteration). 您距离还不太远:您不需要break语句,它会导致早熟的循环中断(在第一次迭代中)。 So here you go: 因此,您在这里:

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))

EDIT : added equivalent of code outside the loop in the original question. 编辑 :在原始问题的循环外添加了等效代码。

Apart from the fact that i don't see where you defined combinationVector , everything should be okay. 除了我看不到您在哪里定义combinationVector ,其他一切都应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM