Asked by Julia Dunn
on 13 Nov 2019

Hello! I am working on a homework assignment where we are given a 1000x1000x1000 logical matrix and we want to create a histogram showing the number of ones in each layer of the matrix. I went through, indexed each of the 1000 layers and counted the number of zeros, but I am now having trouble with the bins on my histogram. I want to plot it so that the x axis has a bar for each of the 1000 layers and the y axis shows how many 1s were in each layer. When I specify the number of bins as 1000, my X axis goes from (0 to 2.5)*10^5 and my y axis goes from 0 to 50, and when I don't specify the bins at all by x axis goes from (0 to 3)*10^5 and my y axis goes from 0 to 900. Is there something wrong with my code that counts the ones, or am I misunderstanding something about histograms and bins? Is what I want to do with my histogram even possible? Thank you!

Answer by Adam Danz
on 14 Nov 2019

Edited by Adam Danz
on 14 Nov 2019

Accepted Answer

What you're describing sounds like a bar chart rather than a histogram. 1000 bars is quite a lot of bars.

data = logical(randi(2,100,100,100)-1); % Fake data (100 x 100 x 100)

count = squeeze(sum(data,[1,2])); % Number of TRUE in each layer (3rd dimension)

bar(count) % The bar plot

If you'd like to use the histogram function instead: histogram('BinEdges',edges,'BinCounts',counts)

histogram('BinEdges',1:101,'BinCounts',count)

% 1:1001 in your case

How do bins in histograms work?

Suppose you have a bunch of random data between 0 and 100 and you want to know how many values there are between 0:5, 5:10, 10:15, ..., 95:100. The histogram function (or the histcounts function) will sort your data into those bins and count the number of points within each bin.

In your case, you're not really working with bins. You want to know the number of 1-values on each layer of your 3D array. If you ask the histrogram function for 1000 bins, it will see that your data (the 1-counts) range from 0 to 10^5 and it will divide that range into 1000 parts. That's not what you want. You already know the "bins" (1,2,3,...,1000, which aren't really bins). Does that make more sense?

Julia Dunn
on 14 Nov 2019

yes that makes sense! Thanks very much

Adam Danz
on 14 Nov 2019

Glad I could help!

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.