1
$\begingroup$

I have a 3d experimental *.txt data with the form: 3d experimental .txt data format 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.

$\endgroup$
1
$\begingroup$

With a file that looks like:

enter image description here

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[[1]]
  (* {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[[#[[1]]]], ys[[#[[2]]]], fs[[#[[1]], #[[2]]]]} & /@ 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]]]}], 1]
$\endgroup$
  • $\begingroup$ thanks a lot! It worked perfectly! $\endgroup$ – Osbel4R Sep 28 at 7:39
  • $\begingroup$ You're welcome! $\endgroup$ – MelaGo Sep 29 at 18:12
1
$\begingroup$

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";
ReadList[myFunctionName, Number, RecordLists -> True]

{{1, 1, 1, 1}, {2, 2, 4, 8}, {3, 3, 9, 27}}

Note: you will have to save the nb file with this code in the same directory as the txt file before you execute the code.

$\endgroup$
  • $\begingroup$ Thank you very much! $\endgroup$ – Osbel4R Sep 28 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.