MATLAB: How to transpose a dataset or table

MATLAB

How can I transpose a dataset or table (make the rows and columns switch) in MATLAB R2013b?
For example, I have the following dataset:
>> X = dataset({[1;2], 'a'}, {[100;200], 'b'}, 'ObsNames', {'c','d'})
X =
a b
c 1 100
d 2 200
and I would like to transpose the dataset:
>> Xt = X'
Xt =
c d
a 1 2
b 100 200
Similarly, if I have the same data stored in a table:
>> X = array2table([1 100; 2 200],'VariableNames',{'a','b'},'RowNames',{'c','d'})
X =
*a* *b*
_ ___
*c* 1 100
*d* 2 200
and I would like to transpose the table:
>> Xt = X'
Xt =
*c* *d*
___ ___
*a* 1 2
*b* 100 200
How can I do this?

Best Answer

The ability to transpose a dataset or table using the transpose operator (') is not available in MATLAB R2013b, however this is possible using a combination of other commands.
For datasets, you can use a combination of 'dataset2cell' and 'cell2dataset' to convert the dataset into a cell array, transpose the cell array, then translate back into a dataset:
>> Xc = dataset2cell(X)
Xc =
'ObsNames' 'a' 'b'
'c' [1] [100]
'd' [2] [200]
>> Xt = cell2dataset(Xc','ReadObsNames',true)
Xt =
c d
a 1 2
b 100 200
For tables, you can use a combination of 'table2cell' and 'cell2table':
>> Xc = table2cell(X)
Xc =
[1] [100]
[2] [200]
>> Xt = cell2table(Xc','RowNames',X.Properties.VariableNames,'VariableNames',X.Properties.RowNames)
Xt =
c d
___ ___
a 1 2
b 100 200
As of MATLAB R2018a, you can also use the ROW2VARS function:
<https://www.mathworks.com/help/matlab/ref/rows2vars.html>