如何更快地计算一些嵌套for循环?

时间:2015-06-29 21:51:32

标签: matlab for-loop vectorization

我有四个向量xi1x1xi2x2我将使用以下代码计算p。由于我将拥有许多这些载体,因此根据我需要的时间需要花费很多时间。 有没有办法更快地做到这一点?

xi1 = rand(1,10);
x1 = [1 2 3 4 5];
n1 = length(x1) - 1;
ni1 = length(xi1);
L1 = ones(n1+1,ni1);
for k = 0 : n1 % start the outer loop through the data values for x

    for kk = 0 : (k-1) % start the inner loop through the data values for x (if k = 0 this loop is not executed)
        L1(kk+1,:) = L1(kk+1,:).*(xi1 - x1(k+1))/(x1(kk+1)-x1(k+1)); % see the Lagrange interpolating polynomials
    end % end of the inner loop

    for kk = k+1 : n1  % start the inner loop through the data values (if k = n1 this loop is not executed)
        L1(kk+1,:) = L1(kk+1,:).*(xi1 - x1(k+1))/(x1(kk+1)-x1(k+1)); 
    end % end of the inner loop

end % the end of the outer loop

p1 = prod(L1,1);


xi2 = [1 1.5];
x2 = [1 2 3 4 5];
n2 = length(x2) - 1;
ni2 = length(xi2);
L2 = ones(n2+1,ni2);
for k = 0 : n2 % start the outer loop through the data values for x

    for kk = 0 : (k-1) % start the inner loop through the data values for x (if k = 0 this loop is not executed)
        L2(kk+1,:) = L2(kk+1,:).*(xi2 - x2(k+1))/(x2(kk+1)-x2(k+1)); % see the Lagrange interpolating polynomials
    end % end of the inner loop

    for kk = k+1 : n2 % start the inner loop through the data values (if k = n2 this loop is not executed)
        L2(kk+1,:) = L2(kk+1,:).*(xi2 - x2(k+1))/(x2(kk+1)-x2(k+1)); 
    end % end of the inner loop

end % the end of the outer loop

p2 = prod(L2,1);
p = p1' * p2;

1 个答案:

答案 0 :(得分:0)

你为什么两次用同样的方法?你可以在同一个两个嵌套循环中完成它。

*.png