home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 10 / 10.iso / l / l460 / 3.ddi / DEMOS.DI$ / SPIRAL.M < prev    next >
Encoding:
Text File  |  1993-03-07  |  786 b   |  34 lines

  1. function s = spiral(n)
  2. %SPIRAL    SPIRAL(n) is an n-by-n matrix with elements ranging
  3. %    from 1 to n^2 in a rectangular spiral pattern.
  4.  
  5. %    Copyright (c) 1984-93 by The MathWorks, Inc.
  6.  
  7. % Start in the center.
  8. s = zeros(n,n);
  9. i = ceil(n/2);
  10. j = ceil(n/2);
  11. s(i,j) = 1;
  12. if n==1, return, end
  13.  
  14. % Wind outward from the center.  Use fixed i and increasing j,
  15. % then fixed j and increasing i, then fixed i and decreasing j,
  16. % then fixed j and decreasing i.  Then repeat.
  17. k = 1;  % Numbering.
  18. d = 1;  % Increasing or decreasing.
  19. for p = 1:n
  20.    q = 1:min(p,n-1);  % Note that q is a vector.
  21.    j = j+d*q;
  22.    k = k+q;
  23.    s(i,j) = k;
  24.    if (p==n), return, end
  25.    j = j(p);
  26.    k = k(p);
  27.    i = i+d*q';
  28.    k = k+q';
  29.    s(i,j) = k;
  30.    i = i(p);
  31.    k = k(p);
  32.    d = -d;
  33. end
  34.