matlabmatlab-table

Rearrange MATLAB table variables (Release 2016)


I have a table in MATLAB with variable titles equal to:

titles = {'TZ_1', 'TZ_2', 'TZ_3', 'DATE'};

Is there any way to move change the data to have the DATE before TZ_1?

titles = {'DATE', 'TZ_1', 'TZ_2', 'TZ_3'};

I can see movevars in the 2022 version, but I am currently running the 2016 version.

Any help would be appreciated - I am relatively new to MATLAB.


Solution

  • You can do it by name

    % Set up example data
    t = table(1,2,3,4, 'VariableNames',{'TZ_1', 'TZ_2', 'TZ_3', 'DATE'})
    % Specify the column ordering you want
    titles = {'DATE', 'TZ_1', 'TZ_2', 'TZ_3'};
    % Rearrange the table
    t = t( :, titles );
    

    You can of course do this without the intermediate variable

    t = t( :, {'DATE', 'TZ_1', 'TZ_2', 'TZ_3'});
    

    Extension:

    If you just know you want 'DATE' at the front regardless where it currently is in the order, you could do something like

    titles = [{'DATE'}, setdiff(t.Properties.VariableNames, {'DATE'}, 'stable')];
    t = t( :, titles );