My matlab code with interp3 is not providing me correct answer. Please help.
2 views (last 30 days)
Show older comments
I have a data (shown on left). I have prepared a matlab code (shown on right). The output should have come 13 for (x,y,z)=(1,2,3) but I am getting the value 18. Please show where should I do the necessary correction.
2 Comments
Accepted Answer
More Answers (1)
Cris LaPierre
on 12 Sep 2022
Edited: Cris LaPierre
on 12 Sep 2022
By taking the unique value of X, Y, and Z, you are losing the relationship between the values. Since you have all the data, I'd be inclided to use reshape to have the inputs be 3D arrays. When doing this, note that rows correspond to y, and columns to x. That means needing to sort your data so that the output of reshape correctly organizes the data.
file = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/1123055/interpcheck.csv';
data = readtable(file);
data = sortrows(data,["z","x","y"])
x=reshape(data.x,[3,2,4]);
y=reshape(data.y,[3,2,4]);
z=reshape(data.z,[3,2,4]);
V = reshape(data.result,[3,2,4]);
r = interp3(x,y,z,V,1,2,3)
Your example data set does allow you to use use unique here. You do have to keep in mind that the size of v must be [length(Y) length(X) length(Z)]. However, you can't just arbitrarily make it the size you want. That will cause a disconnect between your x,y,z values and the corresponding result value. This is why you are getting 18. You must either sort the data so that the output of reshape treats the rows as y and columns as x
data = sortrows(data,["z","x","y"])
x = unique(data.x);
y = unique(data.y);
z = unique(data.z);
V = reshape(data.result,3,2,4);
r = interp3(x,y,z,V,1,2,3)
or reshape the data to match the format in the table, and then permute to get it to be what is needed.
x = unique(data.x);
y = unique(data.y);
z = unique(data.z);
V = reshape(data.result,4,3,2);
v = permute(V,[2,3,1]);
r = interp3(x,y,z,v,1,2,3)
3 Comments
Cris LaPierre
on 12 Sep 2022
It does seem like that would be easier, and there is a function for that - griddata, as Stephen23 pointed out.
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!