2015-06-29 50 views
0

我有四個矢量xi1,x1,xi2x2我打算用下面的代碼計算p。因爲我會有很多這些矢量,所以根據我需要的時間花費很多時間。 有沒有辦法做得更快?如何更快地計算一些嵌套for循環?

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; 

回答

0

爲什麼你做兩次同樣的方法?你可以簡單地在相同的兩個嵌套循環中完成。

xi1 = rand(1,10); 
x1 = [1 2 3 4 5]; 
xi2 = [1 1.5]; 
x2 = [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)); 
     L2(kk+1,:) = L2(kk+1,:).*(xi2 - x2(k+1))/(x2(kk+1)-x2(k+1)); 
    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)); 
     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 

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