MATLAB: How to color points from scatter3 (3D scalar field), in accordance with their scalar values

3d3d plotscolorMATLABscatter3

Assume BB matrix is a 3D scalar field containing only {-1,1} The piece of code is (not working..) –
BB = reshape(last,[3*nthroot(cubes,3),3*nthroot(cubes,3),3*nthroot(cubes,3)]);
BB(~BB)=-1;
BBB = abs(fftn(BB)).^2;
[row,col,zz]=ind2sub(size(BBB),find(BBB));
map = [1 0 0
1 1 0];
figure
scatter3(col,row,zz,10,'filled','s');
colormap(map)

Best Answer

I don't have time to give full code, but the first option gives you what you need - i.e a single scatter3 instruction, not a massive nested loop. The 5th argument is an n*3 array of colours where n must be the same size as the number of points in your col, row, zz arrays.
Here is some example code you can hopefully adapt to your case:
e.g.
x = rand( 10,1);
y = rand( 10,1);
z = x.^2 + y.^2;
c = rand( 10, 3 ); % 10 random colours
figure; scatter3( x, y, z, [], c, 'filled' )
will give you a simple scatter plot with different coloured points.
Now all you need to do is, instead of creating 10 random colours as I did there, create a colourmap of the required size e.g.
cmap = [ ones( 256, 1 ), linspace( 0, 1, 256 )', zeros( 256, 1 ) ];
Now you have 256 colours between red and yellow. Your data needs to be binned to index into this colourmap though. This is doable by e.g.
a = rand( 1, 100000 ); % Lots of random continuous data
idx = discretize( a, 256 ); % discretise your data into 256 bins;
(In my original comment above I was going to suggest discretize, but missed that it had an option to supply number of bins rather than explicit edges so this is easier than histcounts which doesn't actually bin your data, it just gives the histogram counts as totals).
Then you have all your data in 256 bins and can use those indices into your colourmap.
c = cmap( idx, : );
should do this for you, and then you can use this as 'c' in my above scatter3 line instead of random colours.