# Advanced: making a 2d or 3d histogram to visualize data density 39

Posted by **Doug Hull**,

**Category:**- Format: Video,
- Level: Advanced

## 39 CommentsOldest to Newest

**1**of 39

**2**of 39

**3**of 39

**4**of 39

**5**of 39

**6**of 39

randx = randn(100000,1); randy = randn(100000,1); z = hist3([randx randy],[40 40]); surf(z)

**7**of 39

>> z = accumarray([xr yr], 1, [n n]);I get the following error:

??? Error using ==> accumarray Third input SZ must be a full row vector with one element for each column of SUBS.Also, can you comment how this differs from hist3.m?

**8**of 39

**9**of 39

xd = randn(100000,1); yd = randn(100000,1); n=49; xi = linspace(min(xd(:)),max(xd(:)),n); yi = linspace(min(yd(:)),max(yd(:)),n); xr = interp1(xi,1:numel(xi),xd,'nearest')'; yr = interp1(yi,1:numel(yi),yd,'nearest')'; z = accumarray([xr yr], 1, [n n]); figure(2) surf(z)I copied everything save the declarations of xd, yd out of your example in the video. Thanks!

**10**of 39

**11**of 39

**12**of 39

**13**of 39

**14**of 39

??? Error using ==> accumarray First input SUBS must contain positive integer subscripts.EngSpd & EngTorq are independant 24000 x 1 vectors SpdBP is a 1x16 vector TrqBP is a 1x21 vector Any ideas on how to fix this issue? Thanks Colin

xd = EngSpd; yd = EngTorq; xi = SpdBP; yi = TrqBP; xr = interp1(xi,1:numel(xi),xd,'nearest')'; yr = interp1(yi,1:numel(yi),yd,'nearest')'; z = accumarray([xr' yr'], 1, [length(SpdBP) length(TrqBP)]); figure(5) surf(z)

**15**of 39

**16**of 39

xr = interp1(xi,0.5:numel(xi)-0.5,xd,'nearest')'; yr = interp1(yi,0.5:numel(yi)-0.5,yd,'nearest')';which requires

z = accumarray([xr yr] + 0.5, 1, [n n]);Best Andrea

**17**of 39

**18**of 39

surf(xi, yi, Z');Why is that? In the example, we have

Z = accumarray([xr yr], 1, [n n]);For instance, if something falls in the 1st X-bin and the 5th Y-bin, it will get counted in Z(1,5). But, the MATLAB plotting commands like SURF and CONTOUR take their inputs in the opposite way: To have something show up at (1,5) in the graph, it should be in Z(5,1). Hope this is useful to the next person who's thinking sideways! -Thomas

**19**of 39

**20**of 39

**21**of 39

**22**of 39

**23**of 39

**24**of 39

**25**of 39

**26**of 39

**27**of 39

**28**of 39

**29**of 39

**30**of 39

**31**of 39

**32**of 39

**33**of 39

**34**of 39

**35**of 39

**36**of 39

**37**of 39

**38**of 39

**39**of 39

## Recent Comments