How to save a column of strings into a NetCDF file?

조회 수: 6 (최근 30일)
Leon
Leon 2020년 3월 10일
댓글: Leon 2020년 3월 10일
If I have a one-column data with a dimension of 200x1 (e.g., Longitude as in the below example), I know how to store them into a NetCDF file by following the below script:
%% define the dimensions:
dim = netcdf.defDim(ncid, 'data_grid', 200);
%% define the variable and variable attributes:
Var_Longitude = netcdf.defVar(ncid, 'LONGITUDE', 'double', dim);
netcdf.putAtt(ncid, Var_Longitude, 'long_name', 'Longitude in decimal degrees');
netcdf.putVar(ncid, Var_Longitude, Longitude);
What if I have a one-column text string with a dimension of 200x1? For example, the string matrix could be like this:
"test1"
"test2"
"test56"
...
Just change the 'double' to 'string"? Anything else I need to change?
  댓글 수: 1
Leon
Leon 2020년 3월 10일
Many thanks for the detailed explanation!
For folks like myself who are not familiar with the differences of string vs char, this is super helpful. I appreciate the tricks to handle trailing spaces.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 3월 10일
편집: Walter Roberson 2020년 3월 10일
You need to char() the string matrix into a char array of constant width, and then you write the 2D char array.
using char() on a string array will blank pad the ends of shorter lines. If some of your strings end in whitespace that are important to preserve, then the opposite operation, string(cellstr(TheCharacterArray)) will trim those blanks out.
If that is not acceptable, you would need to choose a terminator character that you are certain will not occur otherwise, and put it on the end of shorter lines. Something like
S=["test1";"test2";"test567"];
Sc = char(S+'~');
Sc(:,end) = []; %no need for terminator on longest lines
and reverse would be
S_rebuilt = string(regexprep(cellstr(Sc), '~.*$', ''));
This is only needed if you have trailing whitespace you need preserved. Otherwise:
Sc = char(S);
S_rebuilt = string(cellstr(Sc));
Be careful, by the way, as to which dimension gets written first when you write a 2D array of char. You might need to write Sc.' (transpose) to match the standard use inside netcdf, and you might need to transpose when you read it in again,
S_rebuilt = string(cellstr(Sc.'));

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 NetCDF에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by