Reputation: 85
I am trying to access data that are stored in structures in matlab. Having many files I am trying to make the process automatic, however I have a problem in accessing the struct using the structure name (given that it is a string). Also, storing the structure in a variable (as shown below) does not work either, because matlab attaches the whole structure to the variable. Does anybody have an idea on how to do this?
%Initialize variables
Data_Struct = load(dirData(1).name);
file_id = fieldnames(Data_Struct);
data = Data_Struct.Trajectories;
Here a screenshot of the struct containing the data
Upvotes: 0
Views: 85
Reputation: 101
The trick here is to exploit the fact that you can acces to a structure field by its name string as:
name = 'Trajectories'
value = Data_Struct.(name)
So, in your case, to get unrolled values as Cell Array you can use:
%%Little example copying some of your structure
Data_Struct.Trajectories.Labelled = zeros(10);
Data_Struct.Analog = zeros(10);
Data_Struct.FrameRate = 300;
[UnrolledCell] = getUnrolledVal(Data_Struct,[]);
display(UnrolledCell)
UnrolledCell =
3×2 cell array
'Labelled' [10×10 double]
'FrameRate' [ 300]
'Analog' [10×10 double]
Here the getUnrolledVal function is simply:
function [UnrolledCell] = getUnrolledVal(struct_in,UnrolledCell)
fields_list = fieldnames(struct_in);
for i=1:length(fields_list)
field = fields_list{i};
if isstruct(struct_in.(field))
UnrolledCell = getUnrolledVal(struct_in.(field),UnrolledCell);
else
UnrolledCell = [UnrolledCell; {field} {struct_in.(field)}];
end
end
end
Upvotes: 2
Reputation: 434
The file name is changing every time so you need to get the it correctly when loading a new struct.
Data_Struct = load(dirData(1).name);
After this line,
name = fieldnames(Data_Struct);
This will give you the unique name of your file. Finally,
data = Data_Struct.(name{1}).Trajectories.Labelled.(name of the data matrix)
Upvotes: 2