Create array from table with observations with two codes

8 views (last 30 days)
I want to create a matrix based on a table with observations which have two codes to each observation.
Based on the table x I want to get the array at the bottom. I know how I can generate it by making a heatmap, but I am sure there is a much better way. Hopefully there is a function so that I don't need to generate a heatmap and copy the variable from there.
>> x = readtable("C:\matlap_files\tst.csv")
x =
6×3 table
observations code1 code2
____________ _____ _____
100 {'a'} {'a'}
15 {'b'} {'b'}
25 {'c'} {'d'}
111 {'d'} {'d'}
200 {'e'} {'f'}
175 {'f'} {'f'}
>> h = heatmap(x,'code1','code2','ColorVariable',"observations",'ColorMethod','sum')
h =
HeatmapChart (Sum of observations) with properties:
SourceTable: [6×3 table]
XVariable: 'code1'
YVariable: 'code2'
ColorVariable: 'observations'
ColorMethod: 'sum'
Show all properties
>> h.ColorData
ans =
100 0 0 0 0 0
0 15 0 0 0 0
0 0 25 111 0 0
0 0 0 0 200 175

Accepted Answer

Star Strider
Star Strider on 29 Jan 2021
The accumarray function is perfect for this:
x = readtable('Wtst.csv');
[G,code1,code2] = findgroups(x.code1,x.code2);
[Ux1,~,ix1] = unique(x.code1,'stable');
[Ux2,~,ix2] = unique(x.code2,'stable');
tally = accumarray([ix2,ix1], x.observations, [], @sum)
producing:
tally =
100 0 0 0 0 0
0 15 0 0 0 0
0 0 25 111 0 0
0 0 0 0 200 175
.

More Answers (0)

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!