struct to table in matlab

To convert a structure in MATLAB to a table, you can use the struct2table function. This function converts fields of a structure array to tables variables, and outputs a table. Here's an example:

main.m
% Create a sample structure array
myStruct(1).field1 = 1;
myStruct(1).field2 = 'Hello';
myStruct(2).field1 = 2;
myStruct(2).field2 = 'World';

% Convert structure to table
myTable = struct2table(myStruct);

% Display table
disp(myTable)
237 chars
12 lines

This will create a table myTable from the structure array myStruct. Each field from the structure will become a variable in the table.

Alternatively, you can use array2table to convert an array (or cell array) to a table. If your structure can be converted to an array, you can first convert the structure to an array, then convert the array to a table using array2table. Here's an example:

main.m
% Create a sample structure array
myStruct(1).field1 = 1;
myStruct(1).field2 = 'Hello';
myStruct(2).field1 = 2;
myStruct(2).field2 = 'World';

% Convert to array
myArray = struct2array(myStruct);

% Convert array to table
myTable = array2table(myArray, 'VariableNames', {'field1', 'field2'});

% Display table
disp(myTable)
324 chars
15 lines

This will create the same table as the first example, but using array2table instead. Note that we also specify the variable names using the 'VariableNames' argument.

related categories

gistlibby LogSnag