Create some random data of the specified size and range:
Introduce some data near (0,0), for illustration purposes:
Xpos(20:26) = rand(7,1)-0.5;
Ypos(20:26) = rand(7,1)-0.5;
I'm going to use histcounts2 to do 2d histogram binning on this data, and then map the counts to colors for the scatter plot.
First, define the bin edges for histcounts2:
Now, perform 2d histogram counts. Output c is a matrix of counts. in general, it contains some elements that are 0, because there was no data within those bins. binX and binY are the indices telling us which X- and Y-bin each data point ended up in.
[c,~,~,binX,binY] = histcounts2(Xpos,Ypos,x_edges,y_edges);
We need to transform those binX and binY indices into linear indices in the count matrix c. I use sub2ind for that.
idx = sub2ind(size(c),binX,binY);
And then keep only those c values. (Note that, of course, multiple data points can end up in the same bin, which means that idx can have repeated values.)
So now c is a column vector the same size as binX and binY (and Xpos and Ypos), and c tells us the count # of the bin for each (Xpos,Ypos) point.
Now, create the colormap to use. min_c is the minimum count in any bin (remember c is now the bin counts for the data, so c has no zero elements anymore). max_c is the maximum count in any bin. cmap is a 'jet' colormap with ncolors colors.
Now use ind2rgb to map the counts in c into RGB colors, according to the colormap cmap. Note that ind2rgb for integer-type data maps 0 to the first color in the colormap, but in this case we want the minimum value of c (i.e., min_c, the lowest number of counts in a bin) to map to the first color, so we subtract off min_c from c before converting to integer and sending to ind2rgb. Then permute the result so it's ncolors-by-3 instead of ncolors-by-1-by-3.
RGB = permute(ind2rgb(uint8(c-min_c),cmap),[1 3 2]);
Finally, scatter plot the data with those colors,
scatter(Xpos,Ypos,[],RGB,'.')
set up ticks and grid for illustration of the bins used,
and set up the colormap and colorbar.
cb.Ticks = (1:2:2*ncolors-1)/(2*ncolors);
cb.TickLabels = 1:ncolors;
cb.Label.String = 'Bin Count';