フィルターのクリア

Vectorize the loops within the function

1 回表示 (過去 30 日間)
AM
AM 2020 年 2 月 12 日
コメント済み: AM 2020 年 2 月 19 日
Hi, I am trying to create a function for Lagrange's interpolation and I wanted to know if there is a way to vectorize it that makes the code run faster
function y=lagrange(xx,yy,x)
% xx and yy are vectors of data values, x is the vector I want to interpolate
n=size(xx,2);
y=zeros(1,length(x));
for k=1:length(x)
for i=1:n
L=1;
for j =1:n
if j~=i
L=L*(x(k)-xx(j))/(xx(i)-xx(j));
end
end
y(k) =y(k)+yy(i)*L;
end
end
end
I tried to do the following but the code is actually slower
for k=1:length(x)
for i=1:n
j=1:n;j(j==i)=[];
L=prod((x(k)-xx(j))./(xx(i)-xx(j)));
y(k) =y(k)+yy(i)*L;
end
end
Any help is appreciated, thank you!
  2 件のコメント
darova
darova 2020 年 2 月 12 日
Vectorized code is not always faster
Sometimes code is more readable with for loops
AM
AM 2020 年 2 月 19 日
I see, thank you!

サインインしてコメントする。

採用された回答

Srivardhan Gadila
Srivardhan Gadila 2020 年 2 月 18 日
In line 3 of the vectorized code, replace 'j(j==i)=[];' with 'j(i) = [ ];' as it takes time for finding i, which in this case is not needed and also consider declaring any fixed array before itself and not inside for loops.
n=size(xx,2);
y=zeros(1,length(x));
nvec = 1:n;
for k=1:length(x)
for i= nvec
j=nvec;j(i)=[];
y(k) =y(k)+yy(i)*prod((xx(j)-x(k))./(xx(j)-xx(i)));
end
end
Vectorized code often runs much faster than the corresponding code containing loops but not always. Please refer to the following for more information Vectorization.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by