4
votes

I have been trying to display solid black gridlines using the imagesc function, such that each pixel has a black boundary around it. I have tried a few methods, but it seems that no matter what, the lines always go through the pixel. As an example, for imagesc(randn(21,21)), I am trying to get a plot where each square (ie. pixel) here has a black border.

I found one solution here: In matlab, how to draw a grid over an image, but I am unsure how to get it to work with imagesc, and not a.jpg image.

I have also tried using the hold on function to place the lines manually. But every solution, it seems that the grid lines pass through the middle of the pixel. Any help would be appreciated. Thank you.

4

4 Answers

5
votes

Try the following:

imagesc(randn(21,21))
hold on;
for i = 1:22
   plot([.5,21.5],[i-.5,i-.5],'k-');
   plot([i-.5,i-.5],[.5,21.5],'k-');
end

EDIT: The thing is the centers of the pixels are at the integer lattice points, so to outline the pixels you need to use coordinates that ends on .5.

5
votes

pcolor does exactly that:

pcolor(randn(15,21))
axis image %// equal scale on both axes
axis ij %// use if you want the origin at the top, like with imagesc

enter image description here

1
votes

Extention to @luis-mendo 's answer

As @Girardi mentioned, pcolor displaces the matrix contents. For example:

i = eye(5);
pcolor(i);
axis image %// equal scale on both axes
axis ij %// use if you want the origin at the top, like with imagesc

gives Note: Shows 4x4 instead of 5x5

Note that it gives 4x4 instead of 5x5. Solution: Pad the matrix with zeros


i = eye(5);
pcolor([i, zeros(size(i,1), 1); zeros(1, size(i,2)+1)])
axis image %// equal scale on both axes
axis ij %// use if you want the origin at the top, like with imagesc
axis off

gives

Correct

0
votes

If you would like to highlight the diagonal do the following:

    mat=rand(10);
    figure, imagesc(mat)
    colormap gray

    hold on;
    n=size(mat,1);
    for i = 1:n
       plot([.5,n+.5],[i-.5,i-.5],'k-');
       plot([i-.5,i-.5],[.5,n+.5],'k-');
    end

    % Highlight diagonal values
    k=0.5;
    for i=1:numel(diag(mat))
    line([k, i+.5], [i+.5, i+.5], 'Color', 'r', 'LineWidth', 2);
    k=k+1;
    end

    k=0.5;
    for i=1:numel(diag(mat))
    line([k, i+.5], [k, k], 'Color', 'r', 'LineWidth', 2);
    k=k+1;
    end

    k=0.5;
    for i=1:numel(diag(mat))
    line([i+.5, i+.5], [k, i+.5], 'Color', 'r', 'LineWidth', 2);
    k=k+1;
    end

    k=0.5;
    for i=1:numel(diag(mat))
    line([k, k], [k, i+.5], 'Color', 'r', 'LineWidth', 2);
    k=k+1;
    end