user29403543
user29403543

Reputation: 11

Trying to reshape/ rearrange table variables in MATLAB

ID Channel relativeAlpha relativeBeta relativeGamma
01-12 F7 9.25 1.23 2.98
01-12 F8 8.35 3.45 6.78

I'm using EEG lab to calculate relative spectral power for various bands. This went well, but now I'm stuck on how to reshape this the way I need it. I have 20 participants, and I want each participant to have only one row of data.

As such, I'm trying to convert this matrix so that the columns are a combination of electrode and frequency band. For example, each participant would have one row of data with columns labelled F7.relativeAlpha, F7.relativeBeta, and so on (see below for example). Any help would be greatly appreciated!

ID F7.relativeAlpha F7.relativeBeta F7.relativeGamma F8.relativeAlpha F8.relativeBeta F8.RelativeGamma
01-12 9.25 1.23 2.98 8.35 3.45 6.78

I've tried unsuccessfully with the reshape function and with the unstack function.

RelativePowerWide = unstack(RelativePowerResults,'ID','RelativeDelta')

Upvotes: 1

Views: 7

Answers (1)

Wolfie
Wolfie

Reputation: 30017

You could split out a table subset for each unique value of Channel, prefix the measurement columns with the corresponding channel name, and then join the table subsets back together on the ID. Here is an example with similar data to in your question, please see the code comments for more details:

% Set up example data table
ID = [1;1;2;2];
Channel = {'F7';'F8';'F7';'F8'};
Alpha = [9;8;7;6];
Beta = [1;2;3;4];
Gamma = [0.1;0.2;0.3;0.4];

T = table( ID, Channel, Alpha, Beta, Gamma );

% Get the unique channels which need unstacking
channels = unique( T.Channel );
for n = 1:numel(channels)
    % For each channel, get the table subset
    temp = T( strcmp( T.Channel, channels{n} ), : );
    % Remove the redundant Channel column and prefix all non-ID columns
    % with the channel name for this subset
    temp.Channel = [];
    temp.Properties.VariableNames(2:end) = strcat( channels{n}, '_', temp.Properties.VariableNames(2:end) );
    % If this is the first iteration then just assign the temp table to the
    % wide output. Otherwise perform a join on the ID
    if n == 1
        Twide = temp;
    else
        Twide = outerjoin( Twide, temp, 'Keys', 'ID', 'MergeKeys', true );
    end
end

Output:

Twide =
  2×7 table
    ID    F7_Alpha    F7_Beta    F7_Gamma    F8_Alpha    F8_Beta    F8_Gamma
    __    ________    _______    ________    ________    _______    ________

    1        9           1         0.1          8           2         0.2   
    2        7           3         0.3          6           4         0.4  

Upvotes: 0

Related Questions