MATLAB: Building a 2D matrix on top of 1D vector – contour or contour

2d matrixcontourcontourfMATLAB

Hello everyone
I have a matrix of the form below.
0.8147 0.9134 0.2785
0.9058 0.6324 0.5469
0.1270 0.0975 0.9575
The columns are X, Y, and Z. I would like to plot Z value on the the plane XY by the use of contourf function but I don't seem to succed as it asks me two present Z in form of 2D matrix but mine is just a column vector. I am a bit lost and confused and don't know how to do that. The output plot should resemble like the below image.
I wonder if anyone can help. Just note that X=Y=-6.5:6.5. It is symmetric.
clear all
close all
clc
inputFromComsol = importdata('Untitled.txt', ' ', 8);
X = inputFromComsol.data(:,1);
Y = inputFromComsol.data(:,2);
Z = inputFromComsol.data(:,3);
colormap(flipud(gray(256)));
[cITA3mmThreshold,hITA3mmThreshold] = contourf(X,Y,Z,...
'ShowText','off','LabelSpacing',500,'LineStyle','--');
clabel(cITA3mmThreshold,'FontSize',24)
grid;
axis('square');
caxis([0 1]);
set(gca,'FontSize',40);
xlabel('X (mm)','FontSize',40);
ylabel('Y (mm)','FontSize',40);
xticks(-6:2:6)
yticks(-6:2:6)
title('ITA3mmThreshold');
h = imellipse(gca,[-6.5 -6.5 13 13]);
setColor(h,'k');
colorbar

Best Answer

See griddata(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/griddata.html. Following example shows how to convert a matrix of form [x y z] to a 2D grid.
M = rand(100, 3);
x = M(:,1);
y = M(:,2);
z = M(:,3);
xv = linspace(min(x), max(x), 100);
yv = linspace(min(y), max(y), 100);
[Xg, Yg] = meshgrid(xv, yv);
Zg = griddata(x,y,z,Xg,Yg);
contourf(Xg,Yg,Zg);
griddata might give NaN at few location. In that case, you might consider scatteredinterpolant(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/scatteredinterpolant.html