Dustin O'Neal
Dustin O'Neal

Reputation: 23

Matlab Grid Generator

The following is a Matlab code that I got from my Numerical Analysis Textbook. It is used to discretize a Laplacian and setup a matrix based on the chosen domain(in this case a unit square). I was wondering how this code could be modified to change the dimensions of the domain. I.e. a 4 x 5 rectangle. I don't really use Matlab much, but I am curious to see the results for different domains.

N = nx * ny;  
N5 = 5 * N;
irow = zeros(N5, 1);
icol = irow; 
NZA = irow;

index = 0;
row = 0;

for j = 1:ny
   for k = 1:nx

      row = row + 1;

      if j > 1
         index = index + 1;
         NZA (index) = -1.0;
         irow(index) = row;
         icol(index) = row - nx;   % South
      end

      if k > 1
         index = index + 1;
         NZA (index) = -1.0;
         irow(index) = row;
         icol(index) = row - 1;    % West
      end

      index = index + 1;
      NZA (index) = 4.0;
      irow(index) = row;
      icol(index) = row;           % P (self)

      if k < nx
         index = index + 1;
         NZA (index) = -1.0;
         irow(index) = row;
         icol(index) = row + 1;    % East
      end

      if j < ny 
         index = index + 1;
         NZA (index) = -1.0;
         irow(index) = row;
         icol(index) = row + nx;   % North
      end
   end
end            

icol = icol(1:index); 
irow = irow(1:index);
NZA = NZA(1:index);

A = sparse (irow, icol, NZA, N, N);

Upvotes: 0

Views: 264

Answers (2)

Frederick
Frederick

Reputation: 1301

It looks like you can change the size by setting nx and ny.

Upvotes: 2

Autonomous
Autonomous

Reputation: 9075

I don't know about modifying the above code, but I think you can get a mxn grid of points representing a unit square as follows:

%user input
m=4; % points in x-direction
n=5; %points in y-direction

%code
[x,y]=meshgrid(0:1/m:1,0:1/n:1);

%visualization
allPointsOnGrid=[x(:) y(:)];
scatter(allPointsOnGrid(:,1),allPointsOnGrid(:,2));

This will generate a unit square with m+1 points in x-direction and n+1 points in y-direction.

Upvotes: 0

Related Questions