Search code examples
matlabdata-analysisdata-processing

Splitting a table in MATLAB by Sensor ID


I have a large table in MATLAB which contains over 1000 rows of data, in two columns. Column 1 is the ID of the sensor which gathered the data, and column two is the data itself (in this case a voltage).

I have been able to sort my table to gather all the data for sensors together. So, all the data from Sensor 1 is in rows 1 to 100, the data for Sensor 2 is in rows 101 to 179, the data for Sensor 3 is in rows 180 to 310, and so on. In other words, the number of rows which contain data for a given sensor is never the same.

Now, I want to split this main table into separate tables for each sensor ID, and I am having trouble figuring out a way to do it. I imagine I could do it with a loop, where my I cycle through the various IDs, but that doesn't seem like a very, MATLAB way of doing it.

What would be an efficient way to complete this task? Or would a loop really be the only way?

I have attached a small screenshot of some of my data.

enter image description here


Solution

  • The screenshot you shared shows a 1244x1 structure array with 2 fields but the question describes a table. You could convert the structure array to a table using,

    T = struct2table(S);  % Assuming S is the name of your structure
    

    Whether the variable is a structure or table, it's better to not separate the variable and to use indexing instead. For example, assuming the variable is a table, you can compute the mean voltage for sensor1 using,

    mean(T.reported_voltage(strcmp(T.sensor_id,'Sensor1')))
    

    and you could report the mean of all groups using,

    groupsummary(T,'sensor_id', 'mean')
    

    or

    splitapply(@mean,T.reported_voltage,findgroups(T.sensor_id))
    

    But if you absolutely must break apart and tidy, well-organized table, you can do so by splitting the table into sub-tables stored within a cell array using,

    unqSensorID = unique(T.sensor_id);
    C = arrayfun(@(id){T(strcmp(T.sensor_id, id),:)},unqSensorID)