Clear Filters
Clear Filters

How to interpolate a smaller size matrix to a larger size matrix without getting NaN values?

10 views (last 30 days)
I have a matrix of topography heights that were coarsely sampled (101 x 101 datapoints). I want to use those values to populate a 1001 x 1001 matrix. I have the following code (I actually pass the original values from a text file to Z, but here I have it as randomly-generated number so people don't have to download an additional file - the same issue exists regardless).
What I want is the new matrix to have the same (or similar) values at every 10th element of the new matrix, and fill out the regions inside using interpolation. It looks like it is only filling in the first 101 x 101 elements, and assigning NaN values to everything else. What am I doing wrong, and how to fix it?
Z = rand(101,101); % random 101 x 101 matrix
[Xq,Yq] = meshgrid(1:1001); % finer meshpoints, 1001 x 1001
Vq = interp2(X,Y,Z,Xq,Yq,'cubic');
figure
contourf(Xq,Yq,Vq,64,'Edgecolor','none')
colorbar

Accepted Answer

Amish
Amish on 13 Feb 2024
Hi SNIreaPER,
I see that you are facing issues with interpolating the old matrix(101x101) to the new matrix (1001x1001) where NaN values are getting added instead of the interpolated ones.
It looks like there's a small issue with the way the interpolation is set up in your provided code. The original 'x' and 'y' matrices for the coarse grid are not defined, which is needed for "interp2" to know where the original data points are located in the finer grid.
This can be fixed by defining a 'meshgrid' for the initial matrix, use 'linscape' to create a grid for the new matrix and then use 'interp2' using them.
I am attaching a modified version of the code that solves your issue:
% Original 101 x 101 matrix of random topography heights
Z = rand(101,101);
% Define the coarse grid for the original data
[X, Y] = meshgrid(1:101, 1:101); % Coarse meshpoints
% Define the finer grid for interpolation
[Xq, Yq] = meshgrid(linspace(1, 101, 1001), linspace(1, 101, 1001));
% Perform cubic interpolation
Vq = interp2(X, Y, Z, Xq, Yq, 'cubic');
% Plot the interpolated data
figure
contourf(Xq, Yq, Vq, 64, 'Edgecolor', 'none')
colorbar
You can also refer to the following links for refernce:
Hope this helps!

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!