Task: Write a script to read the data in E7.dat which has 4 columns (day, V1, V2,V3). Create a structure to hold these data. Include in the structure the name of the data file and a character array identifying the variable in each column.
Structures are composite variables. They can be used to contain data values along with supporting information.
The following script fragment creates a structure called S containing some data with info on units and a file name:
S.filename='data13.dat'; S.units.time='hours'; S.units.length='meters'; S.time = [ 0 2 3 4 6 7 9 12 15 18 22]; S.length=[10 3 2 6 4 19 24 18 13 9 4]; save('Data.mat','S');All of the information is contained in a variable S. Each sub-variable is referenced by S. followed by the sub-variable name.
As you see with the units variable, sub-variables can themselves have sub-variables.
Structures can be arrays as well. Imagine that you are doing an experiment where you measure properties at a set of locations. Then, the data can be held in the following structure:
Data(1).station=1 % station number Data(1).latitude=37.3; Data(1).longitude=-85.2; Data(1).temp=19; Data(1).wind=25; Data(1).humidity=75; Data(1).elevation=120; % and so forth Data(2).station=2 % station number Data(2).latitude=37.2; Data(2).longitude=-85.3; % and so forth Data(3).station=3 % station number Data(3).latitude=37.1; Data(3).longitude=-85.4; % and so forthThen the location of station 10 is obtained by
disp(['Longitude: ' num2str(Data(10).longitude)]) disp(['Latitude: ' num2str(Data(10).latitude)])
There is no way to create a bunch of entries in a structure. You simply create a structure starting with entry (1) and keep adding. If you create Data(1) and then Data(10), MATLAB will also create entries (2) through (9).
Flow chart for task:
%%% read data file %%% separate data columns %%% create structure with date file name %%% add data columns to structure %%% add cell array for data descriptors %%% add cell array for data units
Script to accomplish task:
%%% read data file %%% separate data columns data=load('E7.dat'); day=data(:,1);V1=data(:,2);V2=data(:,3);V3=data(:,4); %%% create structure with data file name DATA.file='E7.dat'; DATA.dir='../Data'; %%% add data columns to structure DATA.day=day; DATA.V1=V1; DATA.V2=V2; DATA.V3=V3; %%% add cell array for data descriptors DATA.variables={'day: time in days';... 'V1: values for variable 1';... 'V2: values for variable 2';... 'V3: values for variable 3'}; %%% add cell array for data units DATA.units={'days';'meters';'deg C';'mg/L'};