matlabmatlab-struct

How do I find out in which strucutre my matlab variable is stored in?


I have raw data in a .mat format. The Data is comprised of a bunch of Structures titled 'TimeGroup_XX' where xx is just a random number. Each one of these structures contains a bunch of signals and their corresponding time steps.

It looks something like this

TimeGroup_45 = 

                                 time45: [34069x1 double]
                        Current_Shunt_5: [34069x1 double]
                         Voltage_Load_5: [34069x1 double]

This is simply unusable, as I simply do not know where the variable I am looking for is hiding in 100's of the structures contained in the raw data. I just know that I am looking for 'Current_Shut_3' for example!

There has to be a way that would allow me to do the following

for all variables in Work space
      I_S3 = Find(Current_Shut_3)
end for

Basically I do not want to manually click through every structure to find my variable and just want it to be saved in a normal time series instead of it being hidden in a random structure! Any suggestion on how to do it? There has to be a way!

I have tried using the 'whos' command, but did not get far, as it only returns a list of the stored strucutres in the workspace. I cannot convert that text to a variable and tell it to search for all the fields. Thanks guys/girls!


Solution

  • This is a great example of why you shouldn't iterate variable names when there are plenty of adequate storage methods that don't require code gymnastics to get data back out of. If you can change this, do that and don't even bother reading the rest of this answer.

    Since everything is apparently contained in one *.mat file, specify an output to load so it's output into a unified structure and use fieldnames to iterate.

    Using the following data set, for example:

    a1.Current_Shunt_1 = 1;
    a2.Current_Shunt_2 = 2;
    a5.Current_Shunt_5 = 5;
    b1.Current_Shunt_5 = 10;
    save('test.mat')
    

    We can do:

    % Load data
    alldata = load('test.mat');
    
    % Get all structure names
    datastructs = fieldnames(alldata);
    
    % Filter out all but aXX structures and iterate through
    adata = regexpi(datastructs, 'a\d+', 'Match');
    adata = [adata{:}];
    
    queryfield = 'Current_Shunt_5';
    querydata = [];
    for ii = 1:numel(adata)
        tmp = fieldnames(alldata.(adata{ii}));
    
        % See if our query field is present
        % If yes, output & break out of loop
        test = intersect(queryfield, tmp);  
        if ~isempty(test)
            querydata = alldata.(adata{ii}).(queryfield);
            break
        end
    end
    

    which gives us:

    >> querydata
    
    querydata =
    
         5