MATLAB read parameters from text file
Purpose:
I have a text file "param.txt" that stores values like:
lon = 120
lat = 30
...
Now I want to read all these parameters (including names and values) in to MATLAB, and save in a structure.
Solution:
Since the format of param.txt is more or less regular, the best way to do this object is using "importdata". Suppose we want to save in structure 'Param':
V = importdata('param.txt');
Param.fname = 'param.txt';
for i=1:length(V.data)
fieldName = V.textdata{i,1};
fieldValue = V.data(i);
Param = setfield(Param,fieldName,fieldValue);
end
Other Notes:
(1) There are several MATLAB functions that can deal with text files, e.g. load, textread, textscan, sscanf, fscanf, fgets, fgetl, etc.
(2) 'load' is suitable for numbers only, regular (MxN), text file.
(3) 'textscan' read all lines into a cell structure.
(4) 'fgets', 'fgetl' read a single line.
I have a text file "param.txt" that stores values like:
lon = 120
lat = 30
...
Now I want to read all these parameters (including names and values) in to MATLAB, and save in a structure.
Solution:
Since the format of param.txt is more or less regular, the best way to do this object is using "importdata". Suppose we want to save in structure 'Param':
V = importdata('param.txt');
Param.fname = 'param.txt';
for i=1:length(V.data)
fieldName = V.textdata{i,1};
fieldValue = V.data(i);
Param = setfield(Param,fieldName,fieldValue);
end
Other Notes:
(1) There are several MATLAB functions that can deal with text files, e.g. load, textread, textscan, sscanf, fscanf, fgets, fgetl, etc.
(2) 'load' is suitable for numbers only, regular (MxN), text file.
(3) 'textscan' read all lines into a cell structure.
(4) 'fgets', 'fgetl' read a single line.