Generating color map for a 3d grid

I apologize if this question had been asked before, I couldn't find the solution I needed.
I have a 3d grid which I plot using Scatter3 function. Each point in the grid has a value, which I want to translate to a color, any ideas how I do that?
A simple example:
X = 1:10;
Y = 1:10;
Z = 1:10;
Values = rand(10,10,10);
Each point has a correlated value in the Values Mat.
I want to do scatter3(X,Y,Z) But also making each dot to have a color like in normal Jet where the Jet color map is between min(values) to max(values).
P.S. In my real application I have much more dots then the simple line I created for demonstration
I appreciate the help.

 Respuesta aceptada

Voss
Voss el 8 de Mayo de 2022
X = 1:10;
Y = 1:10;
Z = 1:10;
Values = rand(10,10,10);
% 16-color jet colormap
cmap = jet(16);
NC = size(cmap,1);
% set up thresholds for determining which Values get which color
min_value = min(Values(:));
max_value = max(Values(:));
thresholds = linspace(min_value,max_value,NC+1);
thresholds(end) = Inf; % set the uppermost threshold to Inf to avoid missing Values at max_value
% color_idx is indices into cmap
color_idx = zeros(size(Values));
for ii = 1:NC
% Values between two adjacent thresholds ii and ii+1 will get color cmap(ii,:)
color_idx(Values >= thresholds(ii) & Values < thresholds(ii+1)) = ii;
end
% grid for scatter plot
[XX,YY,ZZ] = ndgrid(X,Y,Z);
% scatter plot with marker '.' size 20 and colors cmap(color_idx,:)
scatter3(XX(:),YY(:),ZZ(:),20,cmap(color_idx,:),'.')
% set up and display colorbar for reference
set(gca(),'Colormap',cmap,'CLim',[min_value max_value])
colorbar

4 comentarios

kuku hello
kuku hello el 8 de Mayo de 2022
May I ask a question? Why the operand & works but && doesn't?
Voss
Voss el 8 de Mayo de 2022
Editada: Voss el 8 de Mayo de 2022
&& is only for comparing scalars. In this case, Values is an array, so Values >= thresholds(ii) and Values < thresholds(ii+1) are arrays, so & must be used instead.
Example:
x = magic(3)
x = 3×3
8 1 6 3 5 7 4 9 2
x >= 2 & x < 6
ans = 3×3 logical array
0 0 0 1 1 0 1 0 1
x >= 2 && x < 6 % error
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.
kuku hello
kuku hello el 9 de Mayo de 2022
Thank you very much!
Voss
Voss el 9 de Mayo de 2022
You're welcome!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Productos

Versión

R2020a

Etiquetas

Preguntada:

el 8 de Mayo de 2022

Comentada:

el 9 de Mayo de 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by