Sparse matrix plot matlab

后端 未结 2 1397
Happy的楠姐
Happy的楠姐 2021-01-23 15:31

I have a 5000 *5000 sparse matrix with 4 different values. I want to visualise the nonzero elements with 4 different colors such that I can recognise the ratio of this values an

2条回答
  •  Happy的楠姐
    2021-01-23 15:59

    You could reform the matrix to be a set of [X, Y, F] coordinates (re-using my answer from Resampling Matrix and restoring in one single Matrix):

    Assuming your matrix is M

    [X, Y] = meshgrid(1:size(M,1), 1:size(M,2));
    Mf = M(:); %used again later, hence stored
    V = [X(:), Y(:), Mf];
    

    get rid of the zero elements

    V(Mf == 0, :) = [];
    

    At this point, if you have access to the statistics toolbox you can just go gscatter(V(:,1), V(:,2), V(:,3)) to get the correct plot otherwise continue with the following if you don't have the toolbox:

    Find a list of the unique values in M

    Vu = unique(V(:,3));
    

    For each such value, plot the points as an xy scatter plot, note hold all makes sure the colour changes each time a new plot is added i.e. each new iteration of the loop

    hold all;
    for g = 1:length(Vu)
        Vg = V(V(:,3)==Vu(g),:)
        plot(Vg(:,1), Vg(:,2), '*');
        a{g}=num2str(Vu(g));
    end
    legend(a);
    

    Example M:

    M = zeros(1000);
    M(200,30) = 7;
    M(100, 900) = 10;
    M(150, 901) = 13;
    M(600, 600) = 13;
    

    Result:

    enter image description here

提交回复
热议问题