3

I am trying to accumulate several histogram outputs into a cell array, but it seems that it's impossible to plot or do anything after the first execution of a single histogram command, because it's only an handle to deleted Histogram.

>> x = randn(10000,1);
>> h = histogram(x); 
>> h

h = 

  handle to deleted Histogram
>> whos h
  Name      Size            Bytes  Class                                        Attributes

  h         1x1               104  matlab.graphics.chart.primitive.Histogram              

I am aware that it's possible to write the histogram upon its calculation to a file, How do I save histogram to file in matlab?. Though I am trying to accumulate it into a cell array for later analysis.

Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245
  • 1
    I think I understand what you mean now - after the figure is closed the handle is deleted. – buzjwa Dec 29 '16 at 08:21
  • I would say don't accumulate the handles, just accumulate the binned data from [`histcounts`](https://www.mathworks.com/help/matlab/ref/histcounts.html), and only display them when you need to using [`bar`](https://www.mathworks.com/help/matlab/ref/bar.html). Any changes you want to apply to the plot should be done there. – buzjwa Dec 29 '16 at 08:37

2 Answers2

3

This is due to the BeingDeleted property of histogram which can be read-only so you cannot change it.

However, you can copy the properties in another struct for later use. Modify your code as follows:

x = randn(10000,1);
h = histogram(x);
prop = properties(h);
for i = 1:length(prop)
    newh.(prop{i}) = h.(prop{i});
end

Now all the properties of h are stored in newh which will remain there even after you close the histogram figure.

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
2

As has been suggested in comments, the proper way to do this, if all you need is the histogram values, is to use histcounts:

x = randn(10000,1);
[N,edges] = histcounts(x);

this way you can collect all bins x and y values (edges and N, respectively), and plot them later with bar. Here is a demonstration with a comparison between the results:

subplot 121
h = histogram(x)
title('histogram')
subplot 122
b = bar(edges(1:end-1),N,'FaceColor',lines(1),...
    'FaceAlpha',0.6)
title('bar')

bar vs hist

If it is important to show the histogram in the exact same way that histogarm does, you can set some more properties of bar.

EBH
  • 10,350
  • 3
  • 34
  • 59