Create new column in table from data across multiple columns

4 views (last 30 days)
I have a table with multiple events (P1, P2, N1, early P3, P3) listed in one column, ROI. There are several adjacent columns with latencies that have the same events in their titles. I would like to create a new column (Latencies) with the latencies in the adjacent columns extracted and matched the events in the ROI column. For example if the event under ROI is P1 then under the new column, Latencies, the data in the same row under P1_Max_Lat would be copied. I attached a sample table.

Accepted Answer

Image Analyst
Image Analyst on 4 Nov 2021
Try this:
[rows, columns] = size(sampletable)
tLatencies = table(zeros(rows, 1), 'VariableNames', {'Latencies'})
newTable = [sampletable, tLatencies]
for row = 1 : rows
% Get the event name.
event = newTable.ROI{row}
% Based on that, get the name of the column
% we need to look for to get the data.
columnName = sprintf('%s_Max_Lat', event)
% If that column is there, copy the number to the Latencies column.
if ismember(columnName, newTable.Properties.VariableNames)
% Get data from the appropriate column.
data = newTable.(columnName)(row)
% Put data into the latencies column
newTable.Latencies(row) = data;
fprintf('There is no column called %s in the table.\n', columnName);

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements 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!