MATLAB: How to load text file without header, programmatically specifying names of variables

variable naming

I have a directory of (space-delimited) text files, each of which contain meteorological data for a year. The file name has the form AAA_BBB_YYYY.txt. There are no headers in the .txt files – instead this information is given in a README file.
I would like to load all the files using a loop. The data should be stored as separate column vectors, or a structure of column vectors (or if there's a better way, I'm open to suggestions). The main concern is that I want to be able to specify the year that the data represents, and the name of the variables (e.g. location_1977_temperature, met.location.y1977.temperature). I envisage doing this using strings e.g.
>> loc='mlo';
>> year='y1977';
>> data=[1;2;3];
>> met.(loc).(year).temp = data
met =
mlo: [1x1 struct]
>> met.mlo.y1977.temp
ans =
1
2
3
So the question is how can I achieve the above when I load the data file?
I've generated a function using the data import tool, but this uses (something like a) string literal to assign the variable names e.g.
%%Allocate imported array to column variable names
metmonth = dataArray{:, 2};
I suppose I could do something like
year='1977';data='month';loc='mlo';
met.(loc).(year).(data)=dataArray{: 2};
Is this the recommended way to achieve what I'm trying to do (i.e. I have to use a structure)?

Best Answer

Your code would be much simpler if you used a non-scalar structure rather than dynamically accessing fieldnames like that. Although you could create all of those fieldnames like that, working with them will be quite difficult. A non-scalar array makes accessing data simple:
S(1).data = [0,1;2,3;4,5];
S(1).year = 1977;
S(1).location = 'lmo';
S(2).data = [6,7;8,9;10,11];
S(2).year = 2017;
S(2).location = 'blah';
S(3).data = [12,13;14,15;16,17];
S(3).year = 1988;
S(3).location = 'whatever';
Then accessing your data is trivial, e.g.:
>> idx = strcmp('lmo',{S.location}); % index of "lmo"
>> S(idx).data
ܺans =
0 1
2 3
4 5
>> idy = 1988==[S.year]; % index of 1988
>> S(idy).data
ans =
12 13
14 15
16 17
Note using the meta-data (years, locations) as fieldnames is more complicated because it does not keep code and data separate. Meta-data should be stored as data in its own right: this is simpler and easier to write. Read these to know more: