2

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.

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

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!

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry. numVariables = size(X,2), where X is an input vector column. Also, combinationVector = [0 0 0] initially. Could you kindly add in the last two lines translation too? Thanks!
Sorry skipped a loop. There's another for loop as you can see in the actual Matlab code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.