MATLAB: Regridding 2D-grid shuffled points from 1-D arrays

arraysMATLABmatrix manipulation

Hello,
I have 3 arrays defining a 2D surface, z = f(x, y). My arrays x, y contain the (x,y) pairs of a regular grid, but they are 1-D arrays and not ordered at all. To give you an idea, the arrays x and y are what would come out of:
x_grid, y_grid = meshgrid(1:10, 20:35);
z_grid = sin(x_grid).*cos(y_grid);
aux_shuffle = randperm(length(x_grid(:)));
x = x_grid(aux_shuffle);
y = y_grid(aux_shuffle);
z = z_grid(aux_shuffle);
What I want is to recover my x_grid, y_grid, z_grid out of x,y,z without going ham on nested loops (data set is relatively large, and I don't like the mess anyway). What I am doing right now is totally overkill and inefficient: I am regenerating x_grid and y_grid from x,y and 'interpolating' z into the points from the grid. Since the points I am asking for are the same that are already in the array, I shouldn't be losing any data, but it is slow and dirty:
x_vals = sort(unique(x));
y_vals = sort(unique(y));
[x_grid, y_grid] = meshgrid(x_vals, y_vals);
z_grid = griddata(x, y, z, x_grid, y_grid);
TL;DR: I have a 2D grid of points shuffled into three 1-D arrays x,y,z, and I want to get them back to an ordered, matrix grid structure.

Best Answer

A single SORTROWS command will undo the shuffle
xyz_grid = sortrows([x(:) y(:) z(:)],[1 2]);
ny = find(diff(xyz_grid(:,1)),1,'first'); % ==length(unique(y))
nx = numel(x)/ny; % ==length(unique(x))
xyz_grid = reshape(xyz_grid,[ny,nx,3]);
x_grid = xyz_grid(:,:,1);
y_grid = xyz_grid(:,:,2);
z_grid = xyz_grid(:,:,3);