Pavel
Pavel

Reputation: 77

Interpolating a multidimensional object along two dimensions in Matlab

Suppose there is a 4-dimensional array A of size klmn. I want to obtain an array B of size KLmn by interpolating A along the first two dimensions. More precisely, what I want to do conceptually is in the code below. But how to make it more efficient avoiding the loops? Thank you.

% Initialization
k=10;l=10;m=10;n=10;
K=100; L=100;
B=NaN(K,L,m,n);

% Just for the sake of example:
vec_k=1:k; 
vec_l=1:l; 
vec_K=1:K; 
vec_L=1:L; 
A=zeros(k,l,m,n); 

% Interpolation
for ind_m=1:m
   for ind_n=1:n
      A_aux=squeeze(A(:,:,ind_m,ind_n));
      B(:,:,ind_m,ind_n)=interp2(vec_k',vec_l,A_aux,vec_K',vec_L,'spline');
   end 
end

Upvotes: 1

Views: 70

Answers (1)

Daniel
Daniel

Reputation: 36720

This is what I think you intended to do (changed your code to interpolate within the range of the original matrix):

% Initialization
k=10;l=10;m=10;n=10;
K=100; L=100;
B=NaN(K,L,m,n);

% Just for the sake of example:
vec_k=1:k; 
vec_l=1:l; 
vec_K=linspace(1,k,K); 
vec_L=linspace(1,l,L); 
A=rand(k,l,m,n); 

% Interpolation
for ind_m=1:m
   for ind_n=1:n
      A_aux=squeeze(A(:,:,ind_m,ind_n));
      B(:,:,ind_m,ind_n)=interp2(vec_k',vec_l,A_aux,vec_K',vec_L,'spline');
   end 
end

Which can also be done using interpn

[in{1:4}]=ndgrid(vec_k,vec_l,1:m,1:n);
[out{1:4}]=ndgrid(vec_K,vec_L,1:m,1:n);
X=interpn(in{:},A,out{:},'spline');

Upvotes: 1

Related Questions