table

Methods

Method Reference: table.table2struct

table: S = table2struct (tbl)
table: S = table2struct (tbl, 'ToScalar', true)

Converts a table to a scalar structure or structure array.

S = table2struct (tbl) returns a structure array with the same fields as the variables in tbl. The length of S is the same as the height of tbl.

S = table2struct (tbl, 'ToScalar', true) returns a scalar structure with the same fields as the variables in tbl. Each field has the same rows as the tbl.

The output S does not include any of the table’s properties. This also applies to row names.

Source Code: table

Example: 1

By default table2struct returns a struct array, one element per row, with one field per variable — handy for row-wise iteration.

 LastName = {'Sanchez'; 'Johnson'; 'Li'};
 Age = [38; 43; 38];
 Height = [71; 69; 64];
 T = table (LastName, Age, Height)
T =
  3x3 table

     LastName      Age    Height    
    ___________    ___    ______    

    {'Sanchez'}     38        71    
    {'Johnson'}     43        69    
    {'Li'     }     38        64
 S = table2struct (T);
 S(2).LastName
ans = Johnson
 S(2).Age
ans = 43

Example: 2

Pass 'ToScalar', true to instead get a scalar struct whose fields are whole columns — the layout used by struct2table with 'AsArray', true.

 LastName = {'Sanchez'; 'Johnson'; 'Li'};
 Age = [38; 43; 38];
 Height = [71; 69; 64];
 T = table (LastName, Age, Height)
T =
  3x3 table

     LastName      Age    Height    
    ___________    ___    ______    

    {'Sanchez'}     38        71    
    {'Johnson'}     43        69    
    {'Li'     }     38        64
 S = table2struct (T, 'ToScalar', true)
S =

  scalar structure containing the fields:

    LastName =
    {
      [1,1] = Sanchez
      [2,1] = Johnson
      [3,1] = Li
    }

    Age =

       38
       43
       38

    Height =

       71
       69
       64

Now each field holds every value of that variable at once.

 S.Age
ans =

   38
   43
   38