Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make pivot tables in matlab from a table

Is there an easy way to make pivot tables in matlab from a matlab table? As in as Excel, or pandas.pivot_table in Python? I've found pivottable.m on the file exchange, but it doesn't work with tables.

Here is an example, if I have a table t:

name     value
_____    _____

'Foo'     0   
'Bar'    -1   
'Bar'     5   
'Foo'     1   

And I would like to aggregate on the name column, using the @sum function, to get:

name     sum_of_value
_____    ________

'Bar'    4       
'Foo'    1   

Is there easy way to do this?

like image 482
mjeppesen Avatar asked Feb 19 '16 11:02

mjeppesen


People also ask

What does Pivot do in Matlab?

pivot (MATLAB Function Reference) The result is the matrix matrix pivoted using a Gauss Jordan pivot with pivot element matrix(i,i) . The matrix should be a square matrix. Using all main diagonal elements as pivot elements inverts the matrix.

What is a pivot table Exceljet?

A Pivot Table is a special tool in Excel for summarizing data without formulas. The Pivot Table interface behaves like a report generator, allowing you to interactively add and remove fields as you like. The screen below shows the how fields have been configured to build the pivot table shown above.


1 Answers

You can use grpstats for simple summary tables. However, use unstack to get more complex pivots.

% Example: Create columns from Var1, summing the values for each date:

T = 
    date        item      value
    ________    _______   _______
    2015.2      a         1
    2015.2      a         1
    2015.2      b         1
    2015.2      c         1
    2015.4      a         2
    2015.4      b         2
    2015.4      c         2
    2015.4      d         2
    2016.2      a         3
    2016.2      b         3
    2016.2      c         3
    2016.2      d         3


T2 = unstack(T, 'value', 'item', 'GroupingVariables', 'date', 'AggregationFunction', @sum);

T2 = 
    date        a        b        c        d   
    ________    _____    _____    _____    _____
    2015.2      2        1        1        NaN
    2015.4      2        2        2        2
    2016.2      3        3        3        3
like image 79
Giuseppe Avatar answered Sep 18 '22 23:09

Giuseppe