Search code examples
matlabmatlab-figure

How do I plot matrix in matlab, considering matrix indexes as co-ordinates on a x-y axis


In my following code, region is a matrix 1000x1500. I want to plot values of this matrix on a X-Y chart paper. So, my hypothetical chart paper consists of X values from 1:1000 and Y values from 1:1500.

function plotRegion(region)
    figure;
    [a,b]=size(region);
    hold on;

    for i=1:a
        for j=1:b
            if(region(i,j)>0)
                plot(i,j ,'.' );
            end
        end
    end
    hold off;
end

I am iterating through each value of matrix and whenever I see value greater than 0, I put a dot in my plot. Although the above code is working, it is taking roughly 70 seconds to run on my computer.

I think I am missing something very basic and this can be done in a very efficient and I just cannot think of it. Please help me in rewriting this code so that my purpose is satisfied.

Sample output of my plot code: enter image description here


Solution

  • You can use find instead of iterating region, and use scatter instead of plot

    In case you don't care about the colors of the dots, you can simply do:

    [Y, X] = find(region > 0);
    plot(X, Y, '.')
    

    In case you want to keep the colors:
    Still taking too long...

    [Y, X] = find(region > 0);
    
    for i = 1:length(X)
        plot(X(i), Y(i), '.' );
    end
    

    Consider using scatter instead of plot.
    scatter is more suitable for plotting dots:

    [Y, X] = find(region > 0);    
    C = 1:length(X); %Colors
    C = mod(C, 7);   %Try to fix the colors
    scatter(X, Y, [], C, '.');