Lepidopterist
Lepidopterist

Reputation: 411

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?

Upvotes: 1

Views: 1307

Answers (2)

Osama El-Ghonimy
Osama El-Ghonimy

Reputation: 363

See this

function DrawHeatmap(X,Y,Z)
%DRAWHEATMAP Draw a 2D heatmap for (X,Y) coordinates whose values are in Z
%   X, Y , Z must be columns
%   By: Eng. Osama Talaat Abdel-Hafiz - PhD Student
%   Egypt - Sept 2017
    if size(X,2)==1 && size(Y,2)==1 && size(Z,2)==1
        F = scatteredInterpolant(X,Y,Z); % create a function from interpolation
        [X,Y] = meshgrid(min(X):0.1:max(X),min(Y):0.1:max(Y));
        Z = F(X,Y);
        contourf(X, Y, Z, linspace(floor(min(min(Z))),ceil(max(max(Z))),400), 'LineColor','none')
        colorbar;
    else
        error('X, Y , Z must be columns')
    end
end

Upvotes: 0

Robert Seifert
Robert Seifert

Reputation: 25232

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.

Upvotes: 3

Related Questions