TransWikia.com

Include parameter values with data for safe Export and Import

Mathematica Asked on June 4, 2021

Usually, when saving data as dat. file I include information about the parameters used to generate the data in the file name. Could I include that information with the generated data in the dat. file, in such a way that I can Import and Export it effectively?

For example, assume we have a function $f(x)=a x+ b$ and we would like to obtain the set of data for {$x$, $f(x)$} with different values of $a$ and $b$:

f[x_] = a x + b; a = 1; b = 1;
data = Table[{x, f[x]}, {x, -3, 3, 0.1}]; 

when I use Export["..data.dat", data] this how it looks like

screenshot of exported dat file in Notepad

Can we add a header to the dat. file that contains the values of $a$ and $b$?

I would like something like the following:

screenshot of Notepad, with a=1; b=1 in the first line

One Answer

Consider perhaps a more structured approach to your data, maybe using JSON format or something similar that is built in:

Export[
  "myFile.json",
  {"parameters" -> {"a" -> 1, "b" -> 1}, 
   "data" -> data}, 
  "JSON"
]

This will generate a text file that is still human readable, although of course not as directly as a simple table, but the advantage is that it can be imported back with its metadata intact:

importedData = Import["myFile.json", "JSON"]

(* Out:
{"parameters" -> {"a" -> 1, "b" -> 1}, 
 "data" -> {{-3, -2}, {-2.9, -1.9}, {-2.8, -1.8}, {-2.7, -1.7}, {-2.6, -1.6}, 
            {-2.5, -1.5}, {-2.4, -1.4}, {-2.3, -1.3}, {-2.2, -1.2}, 
            {-2.1, -1.1}, {-2, -1}, {-1.9, -0.9}, {-1.8, -0.8}, {-1.7, -0.7},
            {-1.6, -0.6}, {-1.5, -0.5}, {-1.4, -0.4}, {-1.3, -0.3}, 
            {-1.2, -0.2}, {-1.1, -0.1}, {-1, 0}, {-0.9, 0.1}, {-0.8, 0.2}, 
            {-0.7, 0.3}, {-0.6, 0.4}, {-0.5, 0.5}, {-0.4, 0.6}, {-0.3, 0.7},
            {-0.2, 0.8}, {-0.1, 0.9}, {0, 1}, {0.1, 1.1}, {0.2, 1.2}, 
            {0.3, 1.3}, {0.4, 1.4}, {0.5, 1.5}, {0.6, 1.6}, {0.7, 1.7}, 
            {0.8, 1.8}, {0.9, 1.9}, {1, 2}, {1.1, 2.1}, {1.2, 2.2}, 
            {1.3, 2.3}, {1.4, 2.4}, {1.5, 2.5}, {1.6, 2.6}, {1.7, 2.7}, 
            {1.8, 2.8}, {1.9, 2.9}, {2, 3}, {2.1, 3.1}, {2.2, 3.2}, 
            {2.3, 3.3}, {2.4, 3.4}, {2.5, 3.5}, {2.6, 3.6}, {2.7, 3.7}, 
            {2.8, 3.8}, {2.9, 3.9}, {3, 4}}
}
*)

and from that you can get your parameters and data:

"parameters" /. importedData
"data" /. importedData

Correct answer by MarcoB on June 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP