Search code examples
matlabhistogramone-hot-encoding

MATLAB: One-hot matrix to histogram


I have a one-hot-encoded matrix (size 1E6 x 10) where each row represents an observation and each column represents a category. How can I create a histogram to visualize the counts for each category and label the category names in the x-axis (I guess vertically positioned to prevent overlap) rather than just using the column numbers?


Solution

  • If your matrix is M you can get the row-wise sum, as beaker suggested, and use that to plot a bar chart. (since you're talking about labels it's unlikely you need a 'histogram' as such).

    bar (sum (M, 1));
    

    To set the labels to names, you can edit the resulting axes object's properties:

    set (gca, 'xticklabel', {'one', 'two', 'three', 'four', 'five', 'six'});
    

    If you're using Matlab 2014b or later, you can also control the rotation:

    set (gca, 'xticklabelrotation', 90);