MATLAB: Problem with creating structure with empty variables and later filling variables with for loop

emptyfillfor loopMATLABstructstructuresvariables

Hi everyone!
I have a little problem with the following code, where I first create a structure with the variables I want to use and then later on fill them with a loop. When I fill the variables in the structure with the data from csv_data, the variable-names are overwritten or the structure changes?! I don't really understand what or why this is happening, because working with structures is new to me (and I'm not really a Matlab-Pro to begin with).
Any way I can avoid this problem?
I simplified the code a bit, so you can recreate the problem. Check the struct before and after filling with the loop! Before is how I want it to be (but ultimately filled with data of course!).
csv_data = randn([300 5]);
csv_variables = struct('var',struct('lat', [], 'lon', [], 'A', [], 'B', [], 'C', []));
for i = 1:5;
csv_variables(i).var = csv_data(:,i);
end

Best Answer

The way you are accessing the struct within the loop will attempt to give you the ith struct in the struct array csv_variables (appending to the array if necessary). Because of this you end up with a 1x5 struct array, each of which with a single field var. Instead, you want to access the ith field in 'csv_variables.var'. To correct this, you can get the list of field names and then use dynamic field names to set them within your loop.
% get list of fieldnames within var ('lat', 'lon', 'A', 'B', 'C')
fields = fieldnames(csv_variables.var);
for i = 1:numel(fields)
% access the ith field of csv_variables.var and set it to the appropriate data
csv_variables.var.(fields{i}) = csv_data(:, i);
end
For some more info on generating field names from a dynamic expression, see the following: https://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html