I have a loop where I do many extrapolations using interp1 with the flags 'linear' and 'extrap' so I guess it's technically an extrapolation. Now I want to use the same code but do many pairs of extrapolations at the same time. I have two matrices, X and Y where each row is a matching set to be extrapolated for a value xi = 0 but I can't wrap my head around how to make it work. I've been told that it is possible.
Basically, what I want to do is a faster version of this:
for i = 1:n yi = interp1(X(i,:),Y(i,:),0,'linear','extrap') end
But without the loop using interp2. each row n in the matrices X and Y are a matching set to be evaluated independently.
No products are associated with this question.
[M,N]=size(X); yi=zeros(M,1); map=X>=0; [maxval,idx]=max(map,,2);
a = idx==1 & maxval==1; %All X(i,:) are non-negative, extrapolate left b = idx==N | maxval==0; %All X(i,:) are nonpositive, extrapolate right c= ~(a|b); %Interpolation needed
%Extrapolate left e1=X(a,1); c1=Y(a,1); e2=X(a,2); c2=Y(a,2); slopes=(c2-c1)./(e2-e1); yi(a) = c1-slopes.*e1;
%Extrapolate right e1=X(b,end-1); c1=Y(b,end-1); e2=X(b,end); c2=Y(b,end); slopes=(c2-c1)./(e2-e1); yi(b) = c1-slopes.*e1;
%Interpolate (linearly) j = sub2ind([M,N],find(c),idx(c)); e1=X(j-M); c1=Y(j-M); e2=X(j); c2=Y(j); slopes=(c2-c1)./(e2-e1); yi(c) = c1+slopes.*abs(e1);
As others have also pointed out, this is REALLY not what INTERP2 is meant to do. In fact if anything, since there are 3 variables: X, Y, and i, you'd have to use INTERP3. But I think that would be rather inefficient.
Why do you think the FOR loop is a problem? How do you think doing something else will make it any more "stable"?
I can think of ways that might make it faster, but not really any more stable:
[n,m] = size(X) [XS,Xi] = sort(X,2);
YS = Y(bsxfun(@plus,(Xi(:,1:2)-1)*n,(1:n)')); y = YS(:,1) + diff(YS,1,2)./diff(XS(:,1:2),1,2).*(-XS(:,1));