cheatsheet for dealing with structures?
21 views (last 30 days)
Show older comments
One thing that I find hardest in matlab is dealing with structures and extracting information from then. For me it seems there is not enough clear examples how to extract data in different situations. Is there any cheatsheet made for this? whether its data, [data], {data}, [data].', data{i} etc, there should be examples for all of these situations....
here is example; im trying to get all timestamps "timestamp" (for finding duplicate fields) of sub stucture "trainLocations" from every first cell of main structure "trainTraffic". Everything I have tried has been in vain...
trainTraffic(1).trainLocations(1).timestamp == {trainTraffic.trainLocations(1).timestamp}.'
error is : Intermediate dot '.' indexing produced a comma-separated list with 57 values, but it must produce a single value when followed by subsequent indexing operations.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1623303/image.png)
2 Comments
Stephen23
on 21 Feb 2024
Edited: Stephen23
on 21 Feb 2024
"For me it seems there is not enough clear examples how to extract data in different situations. Is there any cheatsheet made for this?"
Perhaps this:
and in the official documentation:
"whether its data, [data], {data}, [data].', data{i} etc, there should be examples for all of these situations...."
None of those have anything (directly) to do with structures. Those are various syntactic-sugar operators and some totally unrelated indexing and transpose operations. Just like every other function or operator MATLAB (or any other programming language for that matter) does not exhaustively list out every single example [], [A], [A,B], [A,B,C], etc. for every single version of A, B, C, etc which can be variables, expressions, function calls, comma-separated lists, etc. Nor should documentation that explains the concatenation operator explain what the transpose operator does... just as the documentation that explains comma-separated lists should not explain how to use every other operator and function.
Consider how many permutations of operators your proposed documentation would have...
Your proposed documentation would be ... truly enormous. It would be difficult to find anything in it.
"im trying to get all timestamps "timestamp" (for finding duplicate fields) of sub stucture "trainLocations" from every first cell of main structure "trainTraffic""
TRAINTRAFFIC is a structure, it does not have cells.
"Intermediate dot '.' indexing produced a comma-separated list with 57 values, but it must produce a single value when followed by subsequent indexing operations."
That error message is explained in detail here:
Accepted Answer
Stephen23
on 21 Feb 2024
Edited: Stephen23
on 21 Feb 2024
"im trying to get all timestamps "timestamp" (for finding duplicate fields) of sub stucture "trainLocations" from every first cell of main structure "trainTraffic"."
It is unclear exactly what you want because your terminology is a bit mixed up. For a start, structures themselves have no cells. I guess that you want to get the first element of the TRAINLOCATIONS field of each element of the structure TRAINTRAFFIC. Anyway, lets take a first look at your data:
trainTraffic = load('traintraffic.mat').trainTraffic
For that you could use a loop (easy) or use ARRAYFUN or use a comma-separated list with a cell array operator. However the situation is made a bit more complex by the fact that some of the TRAINLOCATIONS fields contain empty structures (which clearly do not have a 1st structure element and would throw an error if you tried to access that non-existent element). So we will use some basic indexing to ignore the empty fields:
C = {trainTraffic.trainLocations}; % comma-separated list
X = ~cellfun(@isempty,C);
find(~X) % Elements of trainTraffic with empty trainLocations field.
F = @(s) s(1).timestamp;
Z = cell(size(C));
Z(X) = cellfun(F,C(X),'uni',0);
Also note that some of those timestamps are empty too:
Z{:}
Again we can use some indexing to ignore the empty text and convert the rest to DATETIME:
Y = ~cellfun(@isempty,Z);
D = NaT(size(Z));
D(Y) = datetime(Z(Y), "InputFormat","y-M-d'T'H:m:s.SSS'Z'");
D(:) % lets take a peek
The inconsistent data (i.e. empty structure and cells) makes this more complex to parse. If the data was consistent it would be easier to parse.
4 Comments
Stephen23
on 23 Feb 2024
@Sven Larsen: take a look at the image/diagram here:
Basically each of those lines (i.e. between s(1), .n(1), .a, etc.) is a pointer to another array in memory. Note how e.g. .n(1) and .n(2) are two totally different arrays. That they are separate arrays is not changed just because they coincidentally have the same type (struct) and fieldnames.
More Answers (1)
Hassaan
on 21 Feb 2024
Edited: Hassaan
on 21 Feb 2024
Understanding MATLAB Data Containers
Structures (struct): A structure is a data type in MATLAB that allows for the storage of data of different types and sizes. Structures are accessed in two primary ways:
- Field Access: Use dot notation to access fields within a structure, e.g., struct.fieldName.
- Element Access: For an array of structures, access individual structures using parentheses, e.g., structArray(index).
Cell Arrays ({}): Cell arrays are containers that can hold data of varying types and sizes. There are two main ways to interact with cell arrays:
- Content Access: Use curly braces to access the contents of individual cells, e.g., cellArray{index} retrieves the content of the cell at index.
- Element Access: Use parentheses to access the cell itself as a unit, e.g., cellArray(index) refers to the cell at index without extracting its contents.
Arrays ([]): Arrays are collections of elements of the same type. MATLAB supports various types of arrays, such as numeric arrays, character arrays, and logical arrays.
- Element Access: Use parentheses to access individual elements of an array, e.g., array(index).
Example Problem
Given a structure array trainTraffic with a substructure trainLocations containing a field timestamp, and you want to get all timestamp values from the first trainLocations of each trainTraffic entry.
% Number of elements in trainTraffic
numElements = numel(trainTraffic);
% Preallocate a cell array for timestamps
timestamps = cell(numElements, 1);
% Loop through each element of trainTraffic
for i = 1:numElements
% Access the first trainLocations of each trainTraffic element and its timestamp
timestamps{i} = trainTraffic(i).trainLocations(1).timestamp;
end
% timestamps cell array now contains the desired timestamp values
Explanation
- numel(trainTraffic): Counts how many elements are in trainTraffic.
- Preallocate a cell array timestamps: It's good practice for efficiency and clarity.
- Loop through each trainTraffic: Extract the timestamp from the first trainLocations and store it in the timestamps cell array.
Additional Points:
- Nesting: You can nest these data containers within each other for more complex data structures.
- Specific Methods: Each container type might have additional methods for specific operations, such as adding, removing, or iterating through elements. Refer to the MATLAB documentation for details.
References
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering
Feel free to contact me.
2 Comments
Stephen23
on 21 Feb 2024
Edited: Stephen23
on 21 Feb 2024
"Access elements with dot notation, e.g., struct.field."
No, this is incorrect.
Fields are accessed using dot indexing.
Elements of a structure are accessed using parentheses (just like every other array class in MATLAB).
"Access elements with curly braces, e.g., cellArray{index}."
Again, incorrect.
The cell content is accessed using curly-braces.
Elements of a cell array are accessed using parentheses (just like every other array class in MATLAB).
See Also
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!