1

I have this piece of code:

function Plot2DScatter(img1,img2)
n = size(img1,1);
m = size(img2,1);
axis([0 280 0 280])
hold on
   for i=1:n
       for j=1:m
           x = img1(i,j);
           y = img2(i,j);
           plot(x,y);
       end
   end
end  

it,s a function that will be used in a GUI. img1 and img2 are two 2048*2048 image matrixes.
so you see the loop should be repeated 4194304 times.
my problem is that it takes too much time for the system to complete the operation (about 45 minutes) and cpu-usage is really high. and when it is done so much physical memory (RAM) is needed (about 45 percent) that the computer gets hanged.
Is there anything that I can do to decrease the pressure applied to the system and do the operation faster?

Roney Michael
  • 3,964
  • 5
  • 30
  • 45
Sepideh Abadpour
  • 2,550
  • 10
  • 52
  • 88
  • A small comment: it is a good practice [not to use `i` and `j` as variable nams in Matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab). – Shai Jun 17 '13 at 06:11

1 Answers1

1

In matlab you should try to avoid for loops whenever possible and use matrix expressions instead. What you are trying to do can be done like this:

plot(img1(:),img2(:))

img1(:), and img2(:) convert the images into vectors which can be used directly as input to the plot function. For your purpose it might be even better to use the scatter function which plots your data as circles directly. That is:

function Plot2DScatter(img1,img2)
   scatter(img1(:),img2(:))
   axis([0 280 0 280]) % note with the axis statement 
                       % afterwards you do not need 'hold on'
end
Shai
  • 111,146
  • 38
  • 238
  • 371
Chrigi
  • 520
  • 5
  • 11