ofithch79
ofithch79

Reputation: 195

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

Upvotes: 1

Views: 202

Answers (2)

adam danz
adam danz

Reputation: 88

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)

Upvotes: 3

Dominic D
Dominic D

Reputation: 1808

In this case the for loop is fine because (I guess) there aren't that many different sensors and your code will likely spend most of its time processing the data anyway - the loop won't give you a significant overhead.

Assuming your table is called t, the following should do what you want.

unique_sensors = unique(t.sensor_id)

for i = 1:length(unique_sensors)
    sensor_data = t(t.sensor_id == unique_sensors(i), :);
    % save or do some processing on this data
end

Upvotes: 3

Related Questions