MATLAB: Make a table from a structure

structurestable

Hi, I want to create a table from a structure that has n fields and I also want the fieldnames to be added as variable names. I have tried the following but I can't find a way to change the column when each field is added:
fnames = fieldnames(data); % get fieldnames
T = table; %assign table to T
for i = 1:length(fnames)
x_T = table(num2cell(getfield(data, fnames{i}))); %extract each field into a variable and convert it to a cell array
T = [T; x_T];
end
T.Properties.VariableNames = {fnames{1:i}};

Best Answer

I figured it out ! Apparently the field name should be set to x_T before inserting the variables to the table.
fnames = fieldnames(data);
T = table;
for i = 1:length(fnames)
x_T = table(num2cell(getfield(data, fnames{i})));
x_T.Properties.VariableNames = {fnames{i}};
T = [T, x_T];
end