Home > Mobile >  How to make this for loop run faster?
How to make this for loop run faster?

Time:01-31

I have a data structure and I would like to change the information associated to some of its inputs listed in set1 to 4 using my function. I've written a for loop, but its execution time is very long. Is there any way to speed it up or any other way besides for loop (I can run them separately but it will be a very long script). Thanks in advance...

    Set1= {'Andrew';'Mike';'Jane';'Bill';'Adam'};
    Set2={'Romania';'Ecuador';'Singapore';'Norway';'India';'UK'};
    Set3 = {'Liverpool';'Delhi';'New York'};
    Set4 = {'2003';'1992';'1991';'2018';'2011';'2024';'2020'};
    
for A=1:length(Set1);
    for B=1:length(Set2);
        for C=1:length(Set3);
            for D=1:length(Set4);
    SET1 = Set1{A};
    SET2 = Set2{B};
    SET3 = Set3{C};
    SET4 = Set4{D};
    Data = myfunction(structure, SET1, 65,'Categ1');
    Data = myfunction(structure, SET2, 100,'Categ2');
    Data = myfunction(structure, SET3, 90,'Categ2');
    Data = myfunction(structure, SET4, 76,'Categ1');
            end
        end
    end
end

CodePudding user response:

Your code is slow because you're unnecessarily using 4 nested loops.

You can simply handle each set in a separate loop, as:

for A=1:length(Set1);
    SET1 = Set1{A};
    Data = myfunction(structure, SET1, 65,'Categ1');
end

for B=1:length(Set2);
    SET2 = Set2{B};
    Data = myfunction(structure, SET2, 100,'Categ2');
end

for C=1:length(Set3);
    SET3 = Set3{C};
    Data = myfunction(structure, SET3, 90,'Categ2');
end

for D=1:length(Set4);
    SET4 = Set4{D};
    Data = myfunction(structure, SET4, 76,'Categ1');
end

You can also drop the temporary variable and write loops as:

for A=1:length(Set1);
    Data = myfunction(structure, Set1{A}, 65,'Categ1');
end
 // same for the 3 other loops
  •  Tags:  
  • Related