1

I am thinking of recast a double for loop into something I can use with parallel computing. Specifically, I have

for i = 1 : N
    x = x0+i*dx;
    for j = 1 : N
        y = y0+j*dy;
    end
end

and the main program calls functions that require x and y as input arguments. In my problem the variables x and y are independent and so the two for loops should be able to recast into something simpler that can be run more efficiently taking advantage of matlab's matrix computations.

I'm thinking of creating a nested 2D array like (symbolically):

A = [{x0,y0},{x0,y1},{x0,y2},...,{x0,yN};
     {x1,y0},{x1,y1},{x1,y2},...,{x1,yN};
     ...
     {xN,y0},{xN,y1},{xN,y2},...,{xN,yN}]

i.e. each element in a 2D array is a 2-tuple {xi,yi} formed from the elements of the vectors x and y. Can I create such an object in matlab? If so, how can I call each individual element within each tuple? I need to have a way to call each element, e.g. x2 in {x2,y1}, in this array.

I am thinking of doing this so as to have the program run in parallel with input arguments given by each set of tuple {xi,yi} simultaneously, using the parallel processing toolbox on a GPU.

Many thanks in advance for your help. James

Shai
  • 111,146
  • 38
  • 238
  • 371

1 Answers1

0

I think what you are actually looking for is either meshgrid or ndgrid

>> [x y] = meshgrid( 1:N, 1:N )

For N=3 you'll get

>> [x y] = meshgrid( 1:3, 1:3 )
x =

 1     2     3
 1     2     3
 1     2     3


y =

 1     1     1
 2     2     2
 3     3     3

Now if you want to access a pair you can access its x and y coordinate for each matrix.
For example accessing the coordinates of ii=1, jj=2

>> ii=1; jj=2;
>> [x(ii,jj) y(ii,jj)]

Several comments

  1. If you want both x and y to assume the same range of values (like in this example 1:N), you can skip the second arguemnt of meshgrid

     >> [x y] = meshgrid( 1:N );
    
  2. You can modify the inputs of meshgrid to capture the exact pattern you want for x and y, using dx and dy:

     >> [x y] = meshgrid( x0 + (1:N)*dx, y0 + (1:N)*dy );
    
  3. It is best not to use i and j as variable names in Matlab.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371