Search code examples
matlabstructmatlab-table

Extracting data from struct within matlab table


I have a matlab table. One of the columns consists of 1 by 1 structs. The struct contains two fields called type which is a string and coordinates which is a cell 1x3. I would like to create a 1x3 matrix which contains the values from the 1x3 cell. The table has 3585 rows.

Kind regards Matthias


Solution

  • Supposing you have the following as your structure and your table

    structureName.coordinates={1,2,3}
    structureName.type='type'
    tableName=table(structureName)
    

    You can access the structure using the following code. Note that the '1' is a reference to the index of the table variable you are attempting to access. In this case the structure of interest is the first (and only) variable of the table. Otherwise you would replace '1' with 'n' where 'n' is the index of the structure within your table.

    tableName{:,1}
    

    To access the fields of the structure, you could use:

    tableName{:,1}.type
    tableName{:,1}.coordinates
    

    Assuming you want to create your 1x3 matrix separate from your table, you could use

    cell2mat(tableName{:,1}.coordinates)
    

    For all instances used above you could replace

    tableName{:,1}
    

    with

    tableName.structureName
    

    and get equivalent results.