2
$\begingroup$

I've already read a Q&A stating that because NetCDF does not support primitive string type variables, that it is impossible to export a string to a NetCDF file.

For example:

testvalsnodvar = {"VOL_FRACTION01"}; Export["W:\\LPF_extractor\\test.nc", {"vals_nod_var" ->testvalsnodvar}, "Datasets"]

gives a Java error stating that this is an incorrect format for Datasets. Is there a way around this or am I stuck?

$\endgroup$
2
  • 2
    $\begingroup$ Possible duplicate of Is Mathematica's (v10.0.2) NetCDF exporter broken? $\endgroup$ Commented Apr 30, 2016 at 7:12
  • $\begingroup$ This one can't be closed as a duplicate until the other one is reopened. $\endgroup$ Commented May 10, 2016 at 21:09

2 Answers 2

3
$\begingroup$

Convert the string to a list of integers using ToCharacterCode, and then convert back using FromCharacterCode.

testvalsnodvar = {"VOL_FRACTION01"};
Export["test.nc", {"vals_nod_var" -> 
   ToCharacterCode@testvalsnodvar}, "NetCDF"]
(* "test.nc" *)

Import[
  "test.nc", {"Datasets", "vals_nod_var"}] // FromCharacterCode
(* {"VOL_FRACTION01"} *)
$\endgroup$
2
  • $\begingroup$ That works great for working strictly in Mathematica, however, reading this into another program does not work so well. I suppose there is no way around it if my only option is to convert strings into ASCII code. $\endgroup$ Commented Apr 30, 2016 at 0:33
  • $\begingroup$ From what this page says strings are not a natively supported data type. $\endgroup$ Commented Apr 30, 2016 at 6:09
1
$\begingroup$

No need for workarounds in WL 13.1+:

In[1]:= Export["test.nc", "vals_nod_var" -> {"VOL_FRACTION01"}]

Out[1]= "test.nc"

In[2]:= Import["test.nc", "vals_nod_var"]

Out[2]= {"VOL_FRACTION01"}

By default, Export chooses netCDF-4 format for the file:

In[3]:= Import["test.nc", "Version"]

Out[3]= "NC4 Enhanced"

If you need to Export a string to the classic netCDF data model it will still work, but the string will be exported as an array of characters, thus adding one dimension:

In[4]:= Export["test.nc", "vals_nod_var" -> {"VOL_FRACTION01"}, "Version" -> "Classic"]

Out[4]= "test.nc"

In[5]:= Import["test.nc", "vals_nod_var"]

Out[5]= {{"V", "O", "L", "_", "F", "R", "A", "C", "T", "I", "O", "N", "0", "1"}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.