# How can I convert a matrix of 3d experimental data into a 3d list which can be interpolated in a f(x,y) function

I have a 3d experimental *.txt data with the form: y1 y2 y3 x1 f(x1,y1) f(x1,y2) f(x1,y3) x2 f(x2,y1) f(x2,y2) f(x2,y3) x3 f(x3,y1) f(x3,y2) f(x3,y3)

I need to convert that data into a list as argument for the Interpolation function.

With a file that looks like: data = ToExpression[Import["data.txt", "Table"]]
(* {{y1, y2, y3}, {x1, f[x1, y1], f[x1, y2], f[x1, y3]}, {x2, f[x2, y1],
f[x2, y2], f[x2, y3]}, {x3, f[x3, y1], f[x3, y2], f[x3, y3]}} *)

ys = data[]
(* {y1, y2, y3} *)

xs = data[[2 ;;, 1]]
(* {x1, x2, x3} *)

fs = data[[2 ;;, 2 ;;]]
(* {{f[x1, y1], f[x1, y2], f[x1, y3]}, {f[x2, y1], f[x2, y2],
f[x2, y3]}, {f[x3, y1], f[x3, y2], f[x3, y3]}} *)

xyzdata =
Flatten[Table[{xs[[j]], ys[[i]], fs[[j, i]]}, {j, Length[xs]}, {i, Length[ys]}], 1]

(* {{x1, y1, f[x1, y1]}, {x1, y2, f[x1, y2]}, {x1, y3, f[x1, y3]},
{x2, y1, f[x2, y1]}, {x2, y2, f[x2, y2]}, {x2, y3, f[x2, y3]},
{x3, y1, f[x3, y1]}, {x3, y2, f[x3, y2]}, {x3, y3, f[x3, y3]}} *)


Or alternatively

indices = Tuples[{Range[Length[xs]], Range[Length[ys]]}];
xyzdata = {xs[[#[]]], ys[[#[]]], fs[[#[], #[]]]} & /@ indices

(* {{x1, y1, f[x1, y1]}, {x1, y2, f[x1, y2]}, {x1, y3, f[x1, y3]},
{x2, y1, f[x2, y1]}, {x2, y2, f[x2, y2]}, {x2, y3, f[x2, y3]},
{x3, y1, f[x3, y1]}, {x3, y2, f[x3, y2]}, {x3, y3, f[x3, y3]}} *)


Or all in one step, though I usually prefer a less confusing approach:

xyzdata = Flatten[Table[{data[[1 + j, 1]], data[[1, i]],
data[[1 + j, 1 + i]]}, {j, Length[data] - 1}, {i,
Length[data[]]}], 1]

• thanks a lot! It worked perfectly! – Osbel4R Sep 28 '19 at 7:39
• You're welcome! – MelaGo Sep 29 '19 at 18:12

First just get the data into Mathematica correctly formatted. You have a 2D matrix of data so read it that way. Here's an example: I entered the following data into Notepad and saved it as (space delimited) a txt file:

1 1 1 1

2 2 4 8

3 3 9 27

Now read it into a 2D table:

myFunctionName = NotebookDirectory[] <> "myData.txt";