2

If I have data organized like this:

a c 1
a d 2
b c 3
b d 4

I want to use a and b as my row identifiers and c and d as my column identifiers, yielding a table like this:

  c d
a 1 2
b 3 4

I can accomplish this with a loop in the following manner:

old1 = {'a';'a';'b';'b'};
old2 = {'c';'d';'c';'d'};
dataa = [1 2 3 4]';

tabul = array2table(nan(2,2));
tabul.Properties.RowNames={'a','b'};
tabul.Properties.VariableNames={'c','d'};


for t = 1 : 4

    find1 = strcmp(old1(t),tabul.Properties.RowNames);
    find2 = strcmp(old2(t),tabul.Properties.VariableNames);
    tabul{find1,find2} = dataa(t);

end

Is there a more elegant way to solve this problem? Possible candidates: groupstats? splitapply?

1 Answer 1

3

You can use array2table to directly set the table values, assuming they are sorted (row-major) as in your example.

dataa = [1 2 3 4].';
tabul = array2table(reshape(dataa,2,2).');
tabul.Properties.RowNames={'a','b'};
tabul.Properties.VariableNames={'c','d'};

Also, you can pass the row and variable names directly to array2table:

dataa = [1 2 3 4].';
tabul = array2table(reshape(dataa,2,2).', 'RowNames',{'a','b'}, 'VariableNames', {'c','d'});

Either of the above gives the same result as your example, that is,

tabul = 
         c    d
         _    _
    a    1    2
    b    3    4
1
  • This is good only as far as there are all the possible combinations between {'a','b'} and {'c','d'} in the starting dataset, however. When this is not the case, the do a transposition would require to create missing data points to get a rectangular data matrix to reshape. As far as I know, there is still no 'pivot table' command built in in matlab, but googling it is possible to find around some user package (never tried them however).
    – Giuseppe
    Nov 27, 2015 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.