簡體   English   中英

如何將以下Matlab循環轉換為Python?

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

我一直在努力將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])]

我當然知道其中有一些錯誤。 因此,如果您能幫助我完成轉換並糾正任何錯誤,我們將不勝感激。 提前致謝!

您距離還不太遠:您不需要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 ,其他一切都應該沒問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM