如何使这个 for 循环 运行 更快?

How to make this for loop run faster?

我有一个数据结构,我想使用我的函数将与 set1 中列出的某些输入相关的信息更改为 4。我写了一个for循环,但是它的执行时间很长。有没有什么方法可以加快它的速度,或者除了 for 循环之外的任何其他方法(我可以 运行 它们分开,但这将是一个很长的脚本)。提前致谢...

    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

您的代码运行缓慢,因为您不必要地使用了 4 个嵌套循环。

您可以简单地在单独的循环中处理每个集合,如:

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

您也可以删除临时变量并编写循环:

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