Angelos
Angelos

Reputation: 189

How to plot a grid with different colors for certain points (MATLAB)

The problem

I have a square grid with dimensions NxN and constant spacing between the grid points/nodes. I want to plot this grid, but some points are special and want them to be plotted in different color.

Expectation

The expected plot should look like that, but some blocks must have different color!

enter image description here

Code

My ridiculous and slow solution is given below:

N = 80;
x = 1:1:N;
y = 1:1:N;

rx = randi([1 80],1,1000); %represents the x coordinates of the special points 
ry = randi([1 80],1,1000); %represents the y coordinates of the special points 

[X,Y] = meshgrid(x,y);
Z = zeros(80,80);
figure(1)
surf(X,Y,Z);

%Abandon surf, use scatter instead
figure(2)
for i=1:N
    for j=1:N        
        plot(x(i),y(j),'bo');
        hold on
    end
end

for i=1:1000
    plot(rx(i),ry(i),'ro');
    hold on    
end
grid on    

What is the correct way to do it because my eyes are bleeding? Thank you very much.

Upvotes: 2

Views: 444

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

The color is controlled by Z. So make Z a different value.

linear_indx=sub2ind([N,N],rx,ry);
Z(linear_indx)=1;

Change the colormap (or make your own) for a different set of colors. Or use surf(X,Y,Z,C).

enter image description here

Upvotes: 2

Related Questions