Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Square Spiral

Subject: Square Spiral

From: Thomas Bunn

Date: 5 Nov, 2012 19:11:08

Message: 1 of 4

TL = 100;

dx = 1; dy = 1;
x(1) = 0;y(1) = 0;

i = 2;
n = 1;

while i <= TL
    for j = 1 : n
    x(i) = x(i-1);
    y(i) = y(i-1) + dy;
    i = i + 1;
    if i > TL, break, end;
    end
    if i > TL, break, end;
    for j = 1 : n
    x(i) = x(i-1) + dx;
    y(i) = y(i-1);
    i = i + 1;
    if i > TL, break, end;
    end
    n = n + 1;
    dx = -dx;
    dy = -dy;
end

plot(x,y);
axis([2*min(x) 2*max(x) 2*min(y) 2*max(y)]);

Subject: Square Spiral

From: Thomas Bunn

Date: 7 Nov, 2012 16:48:11

Message: 2 of 4

"Thomas Bunn" wrote in message <k7930c$8t2$1@newscl01ah.mathworks.com>...
> TL = 100;
>
> dx = 1; dy = 1;
> x(1) = 0;y(1) = 0;
>
> i = 2;
> n = 1;
>
> while i <= TL
> for j = 1 : n
> x(i) = x(i-1);
> y(i) = y(i-1) + dy;
> i = i + 1;
> if i > TL, break, end;
> end
> if i > TL, break, end;
> for j = 1 : n
> x(i) = x(i-1) + dx;
> y(i) = y(i-1);
> i = i + 1;
> if i > TL, break, end;
> end
> n = n + 1;
> dx = -dx;
> dy = -dy;
> end
>
> plot(x,y);
> axis([2*min(x) 2*max(x) 2*min(y) 2*max(y)]);

Subject: Square Spiral

From: Thomas Bunn

Date: 7 Nov, 2012 17:53:08

Message: 3 of 4

What is best routine for finding this set of {x,y}?

Subject: Square Spiral

From: Roger Stafford

Date: 8 Nov, 2012 00:41:14

Message: 4 of 4

"Thomas Bunn" wrote in message <k7930c$8t2$1@newscl01ah.mathworks.com>...
> TL = 100;
>
> dx = 1; dy = 1;
> x(1) = 0;y(1) = 0;
>
> i = 2;
> n = 1;
>
> while i <= TL
> for j = 1 : n
> x(i) = x(i-1);
> y(i) = y(i-1) + dy;
> i = i + 1;
> if i > TL, break, end;
> end
> if i > TL, break, end;
> for j = 1 : n
> x(i) = x(i-1) + dx;
> y(i) = y(i-1);
> i = i + 1;
> if i > TL, break, end;
> end
> n = n + 1;
> dx = -dx;
> dy = -dy;
> end
>
> plot(x,y);
> axis([2*min(x) 2*max(x) 2*min(y) 2*max(y)]);
> ........
> What is best routine for finding this set of {x,y}?
- - - - - - - -
  Well, here's an alternative code that takes fewer lines. Whether it is better in any other respect is a matter of debate. Certainly it is more obscure.

 n = 4160; % <-- Your TL
 s = [0,1,0,-1];
 t = floor((1+sqrt(4*(0:n-2)+1))/2)+floor(sqrt(0:n-2));
 x = [0,cumsum(s(mod(t-1,4)+1))];
 y = [0,cumsum(s(mod(t,4)+1))];
 plot(x,y,'r-',x,y,'y.')
 axis equal

Roger Stafford

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us