Copying a struct without knowing its full variable name
Show older comments
Hello,
I am extracting data from a datalogger and the struct names are not what I want them to be. I am trying to search for the structs with a string and rename the struct and place it into a new struct (data) (while copying all data fields within the struct) this is what I have. What I have right now, I must know the exact name of the struct to copy. I don't want to have to know the exact name because it might not be the same every time I extract data, but I do know it will have a certain string within it, which is why I search for RPM.
Thanks.
%RPM
vars = who('-regexp', 'RPM');
if isempty(vars) == 0
data.RPM = Eng_170_00_RPM_08;
disp('success')
else
disp('Could not find RPM')
end
5 Comments
Steven Yeh
on 6 Aug 2018
Could you provide a more specific example? Are you trying to replace a field "RPM" of variable "data" with your loaded data "Eng_170_00_RPM_08"? What do you mean by "certain strings"?
Cory Karnick
on 6 Aug 2018
Edited: Cory Karnick
on 6 Aug 2018
"I used uigetfile('.mat') to load the files into the workspace."
The MATLAB function uigetfile does not load any data from any files into MATLAB, it just returns filenames and the corresponding filepaths. I presume that you load the data using load.
"Copying a struct without knowing its full variable name"
I would not recommend doing this. Read this to know why:
Cory Karnick
on 6 Aug 2018
Answers (1)
The simplest solution by far is to load the .mat files into an output argument, which itself is a structure:
S = load(...);
F = fieldnames(S)
which obviously you can process further using regexp or whatever suits your needs. Renaming the field of a structure is not really possible, but it is easy to create a new field and remove the old one: you can easily add/access the field names dynamically, so you don't need to know what they are in advance. The commands rmfield and getfield will likely be useful to you too. The function struct2cell and its complement cell2struct might also be of interest.
Note that load also supports wildcards and regular expressions, so you do not need to load the entire .mat file, you can simply specify which variables you want:
S = load(...,'*RPM*'); % wildcard
S = load(...,'-regexp','RPM') % regular expression
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!