1d linear interpolation vectorization

조회 수: 6 (최근 30일)
Anders Österling
Anders Österling 2015년 2월 27일
댓글: Anders Österling 2015년 3월 2일
Hi all, I have a vectorization problem I wonder if i could get some help with. I just can't seem to get it done.
I have a matrix A with size N*M, where N=200 and M=200000. The numbers in A are random, and cannot be sorted (for technical reasons elsewhere in my code). I have two vectors B and C with size 1*N. I want to use linear interpolation for all M, which can be done using something like
D=zeros(size(M))
Parfor m=1:200000
D(:,)=interp1(M(:,m),A,B);
End
But needless to say this is super slow (it's all part of a large code run in several outer loops). The problem is that I have a new grid in each iteration, Griddedinterpolant would be faster if I had the same grid but new evaluation points since then I could define the interpolant outside of the loop. So I'd like to try to vectorize this code. I wrote a simple linear 1D interpolation routine (see eg loreen shures blog) but I just can't get it to work. Or even if I could loop over N instead of M that would be a huge improvement!
Any help would be amazing!!

채택된 답변

Matt J
Matt J 2015년 2월 27일
편집: Matt J 2015년 2월 27일
If B falls within the boundaries of all domain vectors M(:,m), you can vectorize it by pre-incrementing all the M(:,m) and stitching them together,
Mmax=max(M);
Mmin=min(M);
z=cumsum([0,Mmax(1:end-1)-Mmin(2:end)+1]);
Anew=repmat(A,1,size(M,2));
Bnew=bsxfun(@plus,B,z);
Mnew=bsxfun(@plus,M,z);
D=interp1(Mnew(:),Anew(:),Bnew)
  댓글 수: 3
Matt J
Matt J 2015년 2월 28일
You can easily detect those B that are out of bounds and post-process to your liking. By default, interp1 sets these to NaN and that's what I do below, but you can obviously post-process the out-of-bounds B in other ways if you wish.
outofbounds=bsxfun(@lt,Bnew, Mnew(1,:)) | bsxfun(@gt,Bnew, Mnew(end,:));
D(outofbounds)=NaN;
Anders Österling
Anders Österling 2015년 3월 2일
Hi,
Excellent tip - it worked like a charm and is extremely fast!
Thanks a lot!! /A

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by