0

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 enter image description here

6
  • Can you upload one test case, or the screenshot of how the data is organized in the struct? Commented Dec 3, 2018 at 9:44
  • sure, I just edited the question Commented Dec 3, 2018 at 9:59
  • What's inside the Trajectories? If another struct called 'Labeled', then what's inside of this? Commented Dec 3, 2018 at 10:02
  • Yes inside Trajectories, there is another structure called Labelled, and then a matrix of data Commented Dec 3, 2018 at 10:18
  • data = Data_Struct.Trajectories.Labelled.(name of the data matrix) This will provide the data matrix as a variable. Commented Dec 3, 2018 at 10:29

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.