MATLAB: Which depth does any temperature have in the each point of 3D-field

interpolationMATLAB

Hi,
I have a 3D matrix with a water temperature (X x Y x Z dimensions where X and Y are latitude and longitude, Z is a deep). Also, I have a vector with depths (1 x Z dimensions). I need to know which depth does any temperature (f.g., 3 °C) have in the each point of field.
Depths vector has a different discreteness:
depth = [1 5 10 25 50 100];
Temperature array does not always contain 3 °C value, f.g.:
temp(1,1,:) = [5.3 5.0 4.3 3.3 2.7 2.5]);
As a result, I need a X x Y depth field at which the 3 °C temperature was observed.
I think I should use linear interpolation between relevant levels but I have no idea how exactly I can do it. It will be enough if you help me determine the depth at one point of field.
I hope anyone can help me,
Thanks,
Elena

Best Answer

You just need to create an interpolant, Z = F(X, Y, T) and then query it for all X and Y with T = 3. I'm assuming you have vectors for X and Y as well:
%X, Y, Z vectors of longitude and latitude and depth
%temperature: 3D matrix of temperatures
[Xfull, Yfull, Zfull] = ndgrid(X, Y, Z); %creates 3D matrices of X, Y and Z coordinates
TempInterpolant = griddedInterpolant(Xfull, Yfull, temperatures, Zfull); %creates Z = F(X, Y, T)
%now you can query the interpolant wherever you want:
[Xquery, Yquery] = ndgrid(X, Y); %creates 2D arrays of X and Y
Tquery = 3;
ZatTquery = TempInterpolant(Xquery, Yquery, repmat(Tquery, size(Xquery)))