[Tex/LaTex] How to one plot in 3D a matrix with LaTeX

3dmatricespgfplotstikz-pgf

I have a problem with drawing a 3d plot in TikZ. I have a matrix of size (n*m) n is the number of points in the x-direction and m is the number of points in the y-direction and the values in the matrix are the z coordinates. For example the array matrix in (1,2) in z value for point 1 in x direction and point 2 in y direction.
How can I plot this matrix in LaTeX?

EDIT Here is a sample of the matrix I would like to plot (z coordinate), with the row index as the x coordinate and the column index as the y coordinate:

(1.0514 ,1.1092 ,1.2479,1.383, 1.4261) 
(1.1294 ,1.247, 1.36, 1.392, 1.304) 
(1.1049,1.1466, 1.2459, 1.3397, 1.362) 
(1.1257,1.161, 1.2445, 1.3218, 1.3356)

Best Answer

Using the data you provided, here is a simple way to plot the surface:

\documentclass{article}

\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture} 
\begin{axis} 
\addplot3[surf] coordinates{
(0,0,1.0514) (0,1,1.1092) (0,2,1.2479) (0,3,1.3830) (0,4,1.4261)

(1,0,1.1294) (1,1,1.2470) (1,2,1.3600) (1,3,1.3920) (1,4,1.3040)

(2,0,1.1049) (2,1,1.1466) (2,2,1.2459) (2,3,1.3397) (2,4,1.3620)

(3,0,1.1257) (3,1,1.1610) (3,2,1.2445) (3,3,1.3218) (3,4,1.3356)
};
\end{axis}
\end{tikzpicture}

\end{document}

It yields this output

Output

Remark 1 This is a very simple code and it is possible to much more complex things using the pgfplots (cf this webpage).

Remark 2 If your matrix is big, you may want to process it first to get the coordinates in a file rather than entering them manually. For this many options are available using different softwares.

EDIT Another method for the same output (and for big matrices), the idea is adapted from this answer:

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepgfplotslibrary{groupplots} 

\begin{document}

\begin{tikzpicture}
\begin{axis}[view={-65}{45}]
\addplot3[raw gnuplot,surf]
            gnuplot[id={surf}]{%
set pm3d map interpolate 0,0;
splot 'data.txt' matrix using 1:2:($3);};
\end{axis}
\end{tikzpicture}

%This part of the code is here only for comparison purpose
\begin{tikzpicture} 
\begin{axis}[view={-65}{45}]
\addplot3[surf] coordinates{
(0,0,1.0514) (1,0,1.1092) (2,0,1.2479) (3,0,1.3830) (4,0,1.4261)

(0,1,1.1294) (1,1,1.2470) (2,1,1.3600) (3,1,1.3920) (4,1,1.3040)

(0,2,1.1049) (1,2,1.1466) (2,2,1.2459) (3,2,1.3397) (4,2,1.3620)

(0,3,1.1257) (1,3,1.1610) (2,3,1.2445) (3,3,1.3218) (4,3,1.3356)
};
\end{axis}
\end{tikzpicture}

\end{document}

NOTE The data.txt file is the following

1.0514 1.1092 1.2479 1.3830 1.4261
1.1294 1.2470 1.3600 1.3920 1.3040
1.1049 1.1466 1.2459 1.3397 1.3620
1.1257 1.1610 1.2445 1.3218 1.3356

And its output:

Second Output

Related Question