Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading