MATLAB Answers

Interp2.m -- Unclear how to form grid

4 views (last 30 days)
I am trying to plot some data using interp2.m and I am stuck.
I have a K*2 data set, which I wish to plot in 3D, with the 3rd dimension being the frequency of each pair of observations.
I keep getting the error message "The grid was created from grid vectors that were not strictly monotonic increasing."
This is because I am unclear on what format Z needs to be in.
my code is as follows:
%%Make Data
K = 10000;
y = randi([1,200], [K,1]);
x = randi([1,100], [K,1]);
%%how many times do this pair occur?
[C,~,ic] = unique([y x],'rows');
[z IX] = sort(histc(ic, 1:length(ic)), 'descend');
idY = (z==0);
z(idY) = [];
z = z / sum(z); % normalize. PDF.
IX(idY) = [];
y=C(IX,1);
x=C(IX,2);
scatter3(x,y,z,'filled');
Now I wish to plot a mesh/surface on this data and also use interp2 for non-graphical lookups.
1. I wish to be able to plot mesh(x,y,z).
2. I wish to be able to evalaute z_1 = interp2(x,y,z,x_1,y_1, 'spline'), where x_1 and y_1 are values chosen by me.
3. Continuing from (2), if I have x_1 and wish to find the most likely value of z, how can I do this? Do i have to use a for loop and evaluate a vector of y_1 values and then take the max? or is there a better way?
How can I do this?
My attempt to make Z (as per URL) was as follows:
gridx1 = [1 : 1 : max(ceil(x))];
gridx2 = [1 : 1 : max(ceil(y))];
Z = zeros(length(gridx1), length(gridx2));
%Z is a matrix containing the number of observations of that pair
for i = 1: length(gridx1)
for j = 1: length(gridx2)
Z(i,j) = sum( (i == x) & (j == y) );
end
end
Though this doesnt work as Z is 100x200 here. I know it should be KxK. SO I try
Z = zeros(length(x), length(y));
for i = 1: length(x)
for j = 1: length(y)
Z(x(i),y(j)) = Z(x(i),y(j)) + 1;
end
end
but then I get the error I noted above.
Can anyone help? thanks !

Accepted Answer

Sean de Wolski
Sean de Wolski on 25 Jan 2013
Taking a brief look at your code, it appears that you have "scattered" data and not "gridded" data. interp2() requires that your data be gridded, i.e. it should look like the output from meshgrid()
[xx yy] = meshgrid(1:3)
Since you don't have gridded data, you need to use TriScatteredInterp() to create an interpolant and then apply this to the output from meshgrid()
doc TriScatteredInterp
for more information and examples.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by