1

I am writing a Python version of a Matlab program that does 2D histogram. I am making a program that calculates a histogram using the hist3 function in Matlab. And in Python I use the numpy function histogram2d.

So I want to get a 2D histogram based on the input values. The values I input into the program are angle and distance. Angle is the angle value from -180 to 180. And distance from 0 to 100. The bins I use for angle are size 5 and for distance 0.25.

Matlab code:

[N,C]=hist3([distance; angles]',{0:0.25:100; -180:5:180});

My Python version of that code would be:

# define the bins
degree_bins = np.arange(-180, 181, 5)
distance_bins = np.arange(0, 100.001, 0.25)

# calculate the 2D histogram
hist, _, _ = np.histogram2d(df['angle'], df['dist'], bins=(degree_bins, distance_bins))

I am interested in why the degree bins of dimensions 1 x 73 and distance bins of dimensions 1 x 401 in Matlab result in an output histogram of dimensions 401 x 73. While in Python it is 400 x 72.

I assume that Python is dividing the bins between the values I gave it, so the number is reduced by 1. However, how come Matlab has a 73 degree bin?

Or what function to use in Python to get the result like in Matlab?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
milkz-boi
  • 45
  • 3
  • If I remember correctly, Matlab is 1-indexed while python is 0-indexed. That's a very common source for off-by-1 errors. – Dschoni Mar 15 '23 at 13:53
  • @HMH1013 Thank you, that is exactly the answer I was looking for. – Cris Luengo Mar 15 '23 at 14:37
  • The difference between `hist3` and `np.histogram2d` is exactly the same as the difference between `hist` and `np.histogram`, so the linked answer should point out exactly what the problem is and how to get NumPy to give you the same results as in MATLAB. – Cris Luengo Mar 15 '23 at 14:40

0 Answers0