# Torus Demo

## Contents

## Introduction

A **Torus** is a geometric surface that can be represented by a doughnut: from any point on the surface, moving up/down or left/right will eventually lead you back to where you started, to continue on indefinitely. This has the capability of representing an infinite space with a finite amount of material.

The `Torus` datatype provides this functionality by wrapping the raw `TrueData`, and using (one-based) modular arithmetic to extend its space indefinitely. The subscript implementation is meant to be intuitive and match MATLAB's behavior of the builtin datatypes as closely as possible.

An easy example is the need to have the pattern `[1 2 3]` repeated end-over-end in a vector of length 20. A somewhat general solution might look like the following:

x = 1:3; % original data n = 20; y = repmat(x,1,ceil(n/length(x))); % make a new vector that is too big y(1:n) % pick off the first n elements

ans = Columns 1 through 13 1 2 3 1 2 3 1 2 3 1 2 3 1 Columns 14 through 20 2 3 1 2 3 1 2

Doing this with a `Torus` would be much more intuitive and efficient:

T = Torus(1:3); T(1:20)

ans = Columns 1 through 13 1 2 3 1 2 3 1 2 3 1 2 3 1 Columns 14 through 20 2 3 1 2 3 1 2

## Creating a Torus

Create a `Torus` by wrapping the data with the `Torus` constructor:

T = Torus(1:10)

T = Torus with properties: TrueData: [1 2 3 4 5 6 7 8 9 10]

`Torus` requires an input, even if it's empty - `[]` or `{}`.

## Subscripted Reference

Access it as if you had simply done just `T = 1:10`.

T(5:8)

ans = 5 6 7 8

T(end)

ans = 10

Reference out-of-bounds indices:

T(15)

ans = 5

T(-6:2)

ans = 4 5 6 7 8 9 10 1 2

## Subscripted Assignment

`Torus` allows the assignment of values like classic datatypes do. This does not allow non-positive index assignment, but will extend the structure if the index is greater than its current length:

T = Torus(1:10); T(5) = 30; T.TrueData

ans = 1 2 3 4 30 6 7 8 9 10

T(15) = 1; T.TrueData

ans = Columns 1 through 13 1 2 3 4 30 6 7 8 9 10 0 0 0 Columns 14 through 15 0 1

## Cell Arrays

`Torus` can also wrap cell arrays:

T = Torus({'foo','bar','baz'});

T{2}

ans = bar

T{122}

ans = bar

T(5:8,2:7)

ans = 'bar' 'baz' 'foo' 'bar' 'baz' 'foo' 'bar' 'baz' 'foo' 'bar' 'baz' 'foo' 'bar' 'baz' 'foo' 'bar' 'baz' 'foo' 'bar' 'baz' 'foo' 'bar' 'baz' 'foo'

## Higher dimensions

Nothing intuitive should change when using higher dimensions:

T = Torus(magic(5))

T = Torus with properties: TrueData: [5x5 double]

T.TrueData

ans = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9

T(23:25,45:46)

ans = 22 4 3 10 9 11

T(end:end+5,:)

ans = 11 18 25 2 9 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9

## Animating Graphics

Using `Torus` to loop graphics makes for intuitive and straight-forward code with a smaller memory footprint.

Z = peaks; T = Torus(Z); S = surf(T(1:50,1:100)); axis tight manual; for k=1:1e3 set(S,'ZData',T(1:50,k:k+100)) pause(0.01) end