| ¶ Code - xyz2mat | Thursday, Jan 22, 2009 9:45 am |
This is a simple Matlab function I wrote to convert xyz coordinates to a matrix or grid of z-values, which is useful for displaying terrain data as a surface plot.
function mat = xyz2mat(xyz)
%XYZ2MAT Create z-matrix from xyz-values.
% Converts a uniform set of xyz-values into a matrix/grid
% of z-values. In a uniform set, each x-value must have a
% corresponding y-value, and vice versa. The output is a
% structure array, which can be used for things like mesh
% and surface plots.
%
% Version: 0.2
%
% Example:
% surfplot = xyz2mat(xyz(:,1),xyz(:,2),xyz(:,3));
% surf(surfplot.x,surfplot.y,surfplot.z)
%XYZ2MAT Create z-matrix from xyz-values.
% Converts a uniform set of xyz-values into a matrix/grid
% of z-values. In a uniform set, each x-value must have a
% corresponding y-value, and vice versa. The output is a
% structure array, which can be used for things like mesh
% and surface plots.
%
% Version: 0.2
%
% Example:
% surfplot = xyz2mat(xyz(:,1),xyz(:,2),xyz(:,3));
% surf(surfplot.x,surfplot.y,surfplot.z)
x = unique(xyz(:,1));
x = sort(x);
y = unique(xyz(:,2));
y = sort(y);
for i = 1:length(x)
findx = find(xyz(:,1) == x(i));
for j = 1:length(y)
findy = findx(find(xyz(findx,2) == y(j)));
if ~isempty(findy)
z(j,i) = xyz(findy,3);
else
error('Input is not a uniform matrix.');
end
end
end
mat = struct('x',x,'y',y,'z',z);
Linked: Code