# Mesh Grid of a 3d array

25 views (last 30 days)
SA on 21 Jun 2021
Commented: SA on 22 Jun 2021
I want to plot the error when I compare a numerical approximation and an exact solution. I want to use the matlab mesh function (mesh(X,Y,Z)) to visualise the error approximation. With the mesh function the Z component has to be a matrix. My numerical approximation and exact solution are all vectors but they were 3d arrays convected to vectors. How do I use the mesh function to plot the error given that the Z component has to be a matrix? I tried the code below but I am not sure if it's right. Any help will be greatly appreciated. In the code xx (numerical approximation) and yy(exact solution) are vectors of dimension xd^3 and zz is the difference between xx and yy.
xd = nthroot(length(zz),3);
yd = xd;
u = zeros(xd,yd,1);
v = zeros(xd,yd,1);
xstart = -3.0;
xend = 3.0;
h = (xend-xstart)/(xd-1);
x = zeros(xd,1);
y = zeros(xd,1);
for i = 1:xd
x(i) = xstart + (i-1)*h;
y(i) = xstart + (i-1)*h;
end
err = 0.0;
for i = 1:xd
for j = 1:yd
u(j,i,1) = xx((j-1)*xd+i);
v(j,i,1) = yy((j-1)*xd+i);
if abs(u(j,i,1)-v(j,i,1)) > err %error
err=abs(u(j,i,1)-v(j,i,1));
end
end
end
mesh(x,y,u-v);
xlabel('x');
ylabel('y');
zlabel('maxerror');

Joel Lynch on 22 Jun 2021
Edited: Joel Lynch on 22 Jun 2021
So this may be due to confusion about how mesh() works. Mesh produces a 2D surface in a 3D volume, with the Z-axis being the value of the matrix at each X/Y point. If your solution's are truly 3D (a value defined at each X/Y/Z point), mesh cannot really plot any more than one 2D slice at a time (at least cleanly). A good alternative would be to represent error as color in a 3D plot, using slice, but you won't be able to see every point at once.
You could also present the data a few other ways: 1. animated or subplotted 2D frames, plotting 1 2D "slice" at a time, 2. A single Mesh() showing the average or maximum error along the Z axis at each X/Y, and 3. Using something like histogram(err(:)) to see the breakdown of all the errors.
Also, you can greatly simplify the creation of x/y vectors by using linspace:
x = linspace( xstart, xend, nthroot(numel(zz),3) ); y = x;
and you can vectorize (compute all at once) the error generation by:
err = abs(u-v)
The if branch is useless, as error will always be >=0.
SA on 22 Jun 2021
thanks so much Joel. this is what i needed. I appreciate the help.

### Categories

Find more on Surface and Mesh Plots in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!