Search code examples
matlabplotmatlab-figureheatmap

Generate heatmap with coordinates and data stored in vectors


Let A be an n by 3 matrix, such that the first two columns are all ordered pairs of the form (5*i,5*i) for i from 1 to 200. The third column contains values from 0 to 1, which I will call intensities. I want to make a 1000 by 1000 plot so that the rectangle at (5*i,5*i) is shaded with intensity described by the third column entry.

I'm familiar with the heatmap function and imshow, but I don't see a way to include this "scaling by 5" to make a nice plot. And of course in general the x and y coordinates may not be scaled by the same amount.

Is there a nice way to do this in Matlab?


Solution

  • With imagesc it's actually pretty simple:

    First some example data:

    %// generate example data
    ii = 1:200;
    [xx,yy] = meshgrid(ii);
    A(:,1) = 5*xx(:);
    A(:,2) = 5*yy(:);
    A(:,3) = randi([0,1],1,40000);
    

    Actual answer

    n = 200;
    
    %// reshape data
    D = reshape( A(:,3),n,n );
    
    %// heatmap
    imagesc(A(:,1),A(:,2),D)
    colormap(gray)
    caxis([0,1])
    

    gives:

    enter image description here

    Important notice

    If your coordinates are not sorted as required for imagesc you can sort them with:

    A = sortrows(A,[2,1]);
    

    Clown Example

    %// original image
    load clown
    I = reshape(1:numel(X),size(X));
    [R,C] = ind2sub(size(X),I);
    A(:,1) = R(:);
    A(:,2) = C(:);
    A(:,3) = X(:);
    D = reshape( A(:,3),200,320 );
    figure(1)
    subplot(1,3,1)
    imagesc(A(:,1),A(:,2),D)
    
    %// shuffled image -> shuffled data
    shuffle = randperm(320*200);
    A = A(shuffle,:);
    D = reshape( A(:,3),200,320 );
    subplot(1,3,2)
    imagesc(A(:,1),A(:,2),D)
    
    %// sorted image
    A = sortrows(A,[2,1]);
    D = reshape( A(:,3),200,320 );
    subplot(1,3,3)
    imagesc(A(:,1),A(:,2),D)
    

    enter image description here

    You see, even if your coordinates are sorted like a mess, you can rebuild the image with sortrows.