Skip to content
Advertisement

Matlab to Python – Why is nested forloop running twice as often in python?

I need z to be the same index value in Python as in MATLAB, which I think means 991 in Matlab = 990 in Python.

The original MATLAB code (z = 991)

z = 1;
for i = 1:15
    test_timer1 = 1;

    for tester1 = 1:12
        test_timer2 = 1;
        
        for tester2 = 1:12
            
            if test_timer2 > test_timer1
                z = z+ 1;
            end    

            test_timer2 = test_timer2 + 1; 
        end

    test_timer1 = test_timer1 + 1;

    end

end

My Python code (z = 1980)

z=0
for i in range(15):   
    test_timer1 = 0
    
    for tester1 in range(12):
        test_timer2 = 0  
        
        for tester2 in range(12):
            
            if test_timer2 > test_timer1:
                z += 1
                
            test_timer2 += 1 
        
    test_timer1 += 1

Why is my z double the amount? Where is my error? Thanks!

Advertisement

Answer

Your last line (test_timer1 += 1) needs to be indented another step. Right now it’s in your first for loop – you want it in your second.

In matlab, this doesn’t matter because you have the end statement signifying the end of your loop block. In Python, indentation is used to mark blocks.

So it should look like:

z = 0
for i in range(15):
    test_timer1 = 0
    for tester1 in range(12):
        test_timer2 = 0
        for tester2 in range(12):
            if test_timer2 > test_timer1:
                z+=1
            test_timer2 += 1
        test_timer1 += 1
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement