# Category Archives: Tutorial

Tutorial

## Distance...

Mathematica is perfect for working with lists and matrices.  Essentially making it useful for defining and manipulating geometry through rotations and later on analysing the forces through stiffness methods.

A key task when working with series of co-ordinates is to check that the relative distances between points don't change so that the structural elements in between remain the same, even though the structure may have changed position and shape.  When you're working with Mathematica and there's a task that you need to do repeatedly it's often worth creating a custom function that can be called whenever needed.

A couple of the functions that I've written can determine the distance between each co-ordinate in a list for 2D and 3D co-ordinate lists.

First, create some co-ordinates to work with on the examples.

Now that we've got some points to work with we can create a function to determine the distance between the points in 2D.  On 2D points, Mathematica has an inbuilt function called  EuclideanDistance[] which is nice and fast when determining the distance between 2D points.

There are two key parts to the function, the first part maps a list of points across the   EuclideanDistance[] function, with the second section essentially iterating the co-ordinates to restructure the list so that the function can be mapped across the list by rearranging it in a  (First point, Second point)(Second point, Third point) format.... until the last element in the list.

This is nice and zippy for 2D co-ordinates, but won't work unfortunately for 3D and needs modifying to make use of the inbuilt function  Norm[] .

Running a comparison on speed for how 2D points are handled can be compared by zeroing out the Z ordinate.

As can be seen, EuclideanDistance[] is faster, but Norm[] is more flexible and can be used on 2D and 3D co-ordinates.

Tutorial

## Lists...

One of the things that I spend a lot of time doing in Mathematica is creating lists of co-ordinates so that I can export them into structural analysis software, either before or after I've rotated and transformed them through space to mimic a deployable structure.

Most of these methods I've picked up along the way through trawling Stack Exchange which I find a great resource for learning Mathematica, I'm not able to link to all of them as I've hoovered them up into a notebook over a long period of time and not kept all of the original links...

## Creating lists.

Frequently I'll create a list of x co-ordinates, then y co-ordinates, then the z co-ordinates.  There are a multitude of ways to do this, a few of the ways to create a list of co-ordinates are linked below:

Other ways of creating lists, could make use of functions.

{0, 2, 4, 6, 8, 10}

{1, 4, 9, 16, 25}

## Creating points

And there are dozens of other methods that are available, but once you have your list of x, y, and z co-0rdinates then the next step is to combine them.  You could certainly type them in long hand as below, but the more nodes you have the longer it takes.

You could automate a simple list of co-ordinates like above in a couple of ways:

or

Both return the same list of co-ordinates:

{{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}}

## Combining lists.

Or you might have created a list of points, the same as the lists x,y, and z at the top of this post and now want to combine them...

Thread[ ] is available and is one of the quicker methods for knitting together lists.

{{0, 10, 0}, {1, 11, 1}, {2, 12, 2}, {3, 13, 3}, {4, 14, 4}, {5, 15, 5}, {6, 16, 6}}

or

both return.

{{0, 10, 0}, {1, 11, 1}, {2, 12, 2}, {3, 13, 3}, {4, 14, 4}, {5, 15, 5}, {6, 16, 6}}

### Transpose.

Transpose[ ]   can be used for nice tidy syntax

### Inner.

If there is a simple 2D set of co-ordinates, then these can be combined using  Inner[ ]

### Riffle.

Again for simple 2D lists, the function  Riffle[ ] can be used, but needs to be used in combination with  Partition[ ]

If you're working with multiple lists, then a function called multiRiffle can be written, taken from here.

Gives

{{0, 10, 0}, {1, 11, 1}, {2, 12, 2}, {3, 13, 3}, {4, 14, 4}, {5, 15, 5}, {6, 16, 6}}

## Custom functions.

If you only have 2D data points then a function could be written to knit them together, these functions can check to see if the lists are of the same length too which can be beneficial.

{{0, 10}, {1, 11}, {2, 12}, {3, 13}, {4, 14}, {5, 15}, {6, 16}}

Which can be adapted for 3D data points easily enough.

{{0, 10, 0}, {1, 11, 1}, {2, 12, 2}, {3, 13, 3}, {4, 14, 4}, {5, 15, 5}, {6, 16, 6}}

Hopefully this will help someone who's learning Mathematica who's going to be working with data points and co-ordinates a lot.  It seems to be a topic that gets asked a lot on Mathematica Stack Exchange so I thought it would be helpful to try and summarise up in one post.

## Dynamic Arches...

Tinkering about with SystemModeler a little further, I've managed to finally build a sprung arch, complete with dampers on the revolute joints.  I'm intending on using this principle in my research to create folded structures, so it's interesting to see what effect the spring stiffness will have on the behaviour of the arch during the unpacking process - specifically looking at the accelerations on the masses at key points.

The thing that I was struggling with was creating a structure that had a set of equations that could be solved, the key concept I was initially missing was the closing of the structure with the special type of revolute joint to complete the chain.  Without this special revolute chain the equations are essentially unsolvable, so it's important that one of these joints sits in the system somewhere.

Another concept is that the structure in the video has 3 straight segments, each 1m long; but the supports are only 2m apart.... forcing the arch to pop into a stable shape that balances the weights at each of the joints.  This is essentially what makes the arch wobble when solving the initial set of equations.  Next step is applying external forces and measurement points along the structure for displacement etc...

Tutorial

## Searching...

I thought I was pretty good at finding information using Google and other search engines, but after the recent Mathematica seminar I went to I realise that actually I could be searching smarter using Google.

For example, all of the Mathematica documentation sits on one site reference.wolfram.com and I could trawl this if I wanted, or even add the domain into the search field to help give it some focus, maybe even break out some simple BOOLEAN algebra to proper show off.... or I could read how to use Google properly and just constrain all of my search results to this site using site:

For example, entering the following into Google searches the reference.wolfram.com site (and only that site) for the word Transpose.

site:reference.wolfram.com Transpose

Now to take it a step further I could limit all of the responses to be PDF files incase they are tutorials that would be helpful.

site:reference.wolfram.com Transpose filetype:pdf

Give it a whirl on whatever sites you frequently search.

Tutorial

## Rotations...

In a previous post I showed how complex numbers are useful when rotating co-ordinates and since then I've hard coded several geometrical translation and rotation routines that have been crude, but functional in Mathematica.  Nothing too complex, but a nice little achievement, working with matrices and manipulations.

But the scary thing about a big program like Mathematica, is that it has lots of built in functions that whilst incredibly well documented, you have to be aware that they exist before you can start to search for them.

The transformation matrices scripted above, can be automated using some of the inbuilt functions in Mathematica 9.  So for example if I wanted to rotate some co-ordinates about the z-axis the syntax is quite straightforward and can be taken from the documentation.  Rotating 4 co-ordinates (a) around the z axis (b) to give the newly updated co-ordinates (c).

There are quite a few neat and compact examples over on the documentation website if you're interested.

I personally struggle with Mathematica at times, not because the documentation is poor, but because the scope is so vast.  But with helpful sites such as Stack Exchange or the Wolfram Community Page I'm sure I'll start to work my way through some of the more hardcore functions given time.

Tutorial

## ROBOT....

The analysis software of choice at the University is ANSYS and whilst it is a very powerful piece of software it can be a little overwhelming at times for students who are starting to learn how to analyse structures.  Whilst we start them on hand techniques such as moment distribution and then through to matrix methods combined with using LinPRO there's a bit of a jump from those into full blown finite element packages.  One of the good things about being an academic again is that I get access to free copies to all of the AutoDesk software and so I've been giving ROBOT Structural Analysis a whirl to see how I get on.

I've not really used this software in anger yet, but it's comparable to many of the alternative offerings out there that I've used over the years such as QSE, Masterseries, GSA, and SFrame to name a few.  Whilst LinPRO is only 2D, ROBOT brings in the extra dimension to allow 3D frames to be analysed, and importantly for me and the dissertation topics that I offer, it also has the capacity to deal with cables and tension only elements and its this aspect rather than the building modelling that I've been really interested in for the last couple of days.  I started by modelling a simple guyed mast just to see how well it was behaved under dead and live loads.  A nice simple model like this has let me mess about with the different ways of controlling the cable tensions and seeing how the various settings in the analysis engines and element releases work.

After spending a little time getting my head around the releases, for some reason a local x axis restraint doesn't stop the mast spinning with a fixed base, so I had to throw a Global Z restraint to get it to analyse with no warnings...  as a newbie to the software, I'm sure I was probably doing something wrong, but it's all about learning and so there's nothing to beat myself up about.  I was able to get a pretty simple model up and running that seems to be fairly well behaved after about 10 minutes of tinkering which gives an idea of the learning curve involved.

There's a couple of forum posts knocking about that discuss where people have had errors with getting their models to converge, but this appears to be mainly through the application of very large prestress or large change in lengths that are incompatible with each other, meaning that the forces can never balance out based on the criteria set out.  The easiest way I've found to get round this initially is to set the lengths to have a zero change in relative length (as shown below), essentially taking their original starting length with zero prestress or by assigning a very low prestress of say 1kN or 5kN depending on the scale of the system.

After a bit of jigging round, I've managed to get a few different types of cable supported structures behaving themselves, from simple gallow brackets, to cable trusses, and even a simple icosahedron tensegrity prism.... although I need to spend a little more time rotating the geometry to reduce the number of supports needed for the prism.

Now I've got the models behaving and analysing efficiently, I can start to experiment with what difference the various analysis engines make and how they can affect the behaviour of the structure, particularly as I start to increase the complexity into cable nets and stacked tensegrity prisms.  One thing that I'm finding difficult is tracking down a decent ROBOT community, particularly as I think there are quite a few things I could be doing with the API to connect it with Mathematica.

If anyone knows of one, I'd appreciate a heads up or a link....

Tutorial

## Rotating points...

Part of the Mathematica scripts that I've been writing require the generation of curved geometries and I've been spending a bit of time to work through different ways of achieving this.  My initial solutions were quite straightforward and made use of polar co-ordinates to create an array of points, which were then converted to cartesian co-ordinates at the end to make their inclusion in the analysis scripts a little easier.

Another way to do it makes use of complex numbers, but I haven't studied complex numbers for over 20 years and if I'm brutally honest I always struggled to work out what on earth they were really used for in the real world.  I've been through a few texts but the practical applications have always been glossed over.  One line of texts that I've found helpful for rediscovering lost maths skills, specifically for generating geometry, are mathematics books aimed at computer scientists rather than engineers (Vince, 2010).

So what's a complex number?  Essentially a complex number has a real part and an imaginary part and this was the part I used to struggle with as a maths student because I could never understand what use in the real world an imaginary thing could be.  If we could make an imaginary part useful then we could harness the power of unicorns and dragons surely?  This is where Vince (2010) has helped me decipher how complex numbers can be useful as the principles are used in geometry to rotate a point around another point.

And to convert from a simple cartesian co-0rdinate into an equivalent complex number representation is quite straightforward too, you just use the relationship below.

The key concept to understand is that a cartesian co-ordinate can easily be converted to an equivalent complex number and to rotate this new co-ordinate by 90 degrees anti-clockwise you multiply this new complex number by i.  If you want to rotate by a further 90 degrees, then multiply this again by i.  One important thing to remember when going through this series of operations though is that i² can be simplified.

## Example.

So for example if we wanted to take the co-ordinate at point A and rotate it through 90 degrees, we simply multiply the point by i, then simplify and we'll get the new co-ordinate for point B.  Here's the worked example for anyone that wants to follow along at home.

Rotate by 90 degrees, therefore multipy by i.

i² can be simplified to - 1 though

Becoming

Once you've followed the working above, why not have a go at rotating B through 90 degrees to get to point C, then again to get point D and then again to get back to point A?  Essentially multiplying the co-ordinates by i rotates the point 90 degrees in an anti-clockwise direction.

If you wanted to boil this down to a single expression to allow a programme to be coded this can be done quite easily and the expression is as set out below with the angle expressed in terms of degrees.  This expression, takes an existing point (x,y) and rotates it by an angle θ to get the new co-ordinate (x',y')

## Mathematica sample code.

Now we have this simplified expression, let's see how hard it is write a little bit of code to calculate the angle for us using complex numbers.  I don't pretend for a second this code is either elegant or efficient, but for new programmers I think it should be fairly easy to follow.  First we define a variable called coords to input a cartesian co-ordinate, this has to be in between curly brackets.

{-19.94, 392.11}

Next the angle that you wish to rotate between has to be defined, I've assigned this to a variable called angleRot for this example.  This angle has been entered in degrees.

{-49.45}

The next stage applies the equation above for imaginary numbers on the first line of code, with the second line extracting the Real component using the Re[ ] function for the X co-ordinate, and the imaginary component using the Im[ ] function for the Y co-ordinate.

{284.977, 270.066}

This gives the new position based on the co-ordinate being rotated by an angle around the origin (0,0).

## Rotate a point around another specified point.

It's just as straightforward to rotate a point around an arbitrary point rather than the origin it just requires an additional step that moves the co-ordinate back to the origin, then after the rotation has been completed the point is shifted back again by the same amount.

Enter co-ordinates as cartesian.

{3, 2}

Confirm the angle by which you want to rotate the co-ordinate by degrees. All angles are measured positive from 3 o'clock in the anticlockwise direction as per complex numbers standard.

{90}

Now you need to declare the point which you intend to rotate around.

{2, 1}

Before the rotate can begin you need to determine the distance between the origin and the rotate point, this will be the distance you have to translate the point being moved around before the rotation starts.

{-2, -1}

{1, 1}

The final step is to rotate the point around the origin and then move it back by the same amount that it was translated by before rotating.

{1, 2}

## References.

Vince, J. (2010). Mathematics for Computer Graphics (Third ed.). London: Springer.

Tutorial

## Geek Tools...

I've been tinkering around a little bit with GeekTools, which is a Mac utility that allows you to customise your desktop, to try and customise my desktop a little bit to integrate some dynamic components.  I've seen a few interesting desktop arrangements on LifeHacker lately and decided to see if I could nerd it up a little more too with time apps, weather, and basic connection status.

Combining this with a nerdy wallpaper with a Star Wars theme I've managed to pimp my desktop suitably and for a first attempt I'm pretty happy with it.

The time, date, etc are all pretty easy to set up and they can be taken from this link.  However I struggled for quite a while to get the weather app setup to allow real time updating of the weather in my area as Yahoo has changed the way that they create the links and therefore lots of the tutorials that I've found don't quite work anymore because they're based on the old Yahoo Weather codes.

To help future non-US guys set up their own Geek Tools I've listed out the Syntax for a couple of my widgets that gives the Weather in Stockport, these would be easily customised for any other UK city by simply determining the code for your city using the following link.

To create the weather image, you need to add two widgets in Geek Tools, one is an image widget that physically shows the picture, the other one is a shell element that is used to farm the image from the Yahoo site.  The URL that is in red in the syntax below would need to be swapped out for a URL that reflects wherever your location is, and this is simply done by finding your Yahoo Weather site for your city and then copying and pasting this URL to overwrite the red text in the link below.

[Image]
file://localhost/tmp/weather1.png

[Shell]
curl --silent "http://uk.weather.yahoo.com/england/greater-manchester/stockport-36177/?unit=c" | grep "current-weather" | sed "s/.*background\:url(\'$.*$\') .*/\1/" | xargs curl --silent -o /tmp/weather1.png\

The next step is to then get the textual description that goes next to the icon, this is a little trickier as all of the tutorials that I found made use of the RSS feed utility from Yahoo that doesn't appear to exist any longer.  You'll have to work out your city code using this website and then replace the text in blue in the shell element script that you'll create below.

[Shell]
curl --silent "http://weather.yahooapis.com/forecastrss?p=UKXX0140&u=c" | grep -E '(Current Conditions:|C<BR)' | tail -n1 | sed -e 's/<BR \/>//' -e 's/ C\$/˚C/'

Sometimes it can take a few minutes for this to refresh and update onto your desktop, but I found that these were the only scripts that I could get to work and I'm going to stop tinkering anymore with my desktop for a while before I kill it.

## Fibonacci...

I was recently approached to see if I could tinker about and create a short video associated with the Fibonacci series and more specifically the golden ratio for a maths MOOC that's about to launch.  As per usual my inability to say no came into play and then I suddenly realised that I've never created a teaching video before and really what do I know about the Fibonacci series apart from fluffing about with a few Mathematica notebooks, and so blind panic set in... and with blind panic comes a quick trip to XKCD to check out the latest strips for a bit of inspiration...

Now the golden ratio (φ) doesn't sound like the sort of everyday mathematics that you would use will pushing a trolley around TESCO's but the key thing you have to appreciate is that it's a very sneaky number.  Things are that are proportioned using the golden ratio are naturally and inexplicably appealing to the eye, we find the ratio a thing of beauty even though most people don't even know what it is.  It turns out that it's used in everything from composing pleasing photographs (using the rule of thirds as an approximation) through to designing the Parthenon in Greece which is proportioned using this ratio.  It's cool stuff, and to be frank if Mother Nature sees fit to use the principle to establish geometries in plants and other animals... who am I to argue?!

One of the things I like about XKCD are the graphs that they create, they have a certain charm about them and I love the style... and as sketchy as it looks, I've always struggled to replicate these diagrams using Visio or Omnigraffle.

One of my other digital haunts is the Stack Exchange forum, which as a (very) amateur coder I constantly find myself sitting reading through in a sense of amazement at some of the nifty tricks that people pull to make some quite elegant and funky code.  One of the sub-forums I like there is the Mathematica one, which recently asked the question if it was possible to create XKCD graphs using Mathematica, a copy of the thread is here.  I've replicated the code below, as much to save it for myself should the thread ever get closed.

The author of this code has created some sample images using this code and I think they're brilliant.

But coming back to the reason I needed to create some diagrams, the fibonacci sequence and the golden ratio... starting with the golden ratio this is defined by the equation below.

The reason that this number is expressed as a fraction is that it is an irrational number, which means it's similar to π and the decimal places keep on repeating forever with no repetition and so it can't accurately be approximated a decimal.  So how would you approximate this number? Well to start with you need to understand the Fibonacci sequence, which sounds quite grand and complex, but is simple once you understand the trick to determine the sequence... essentially you add together the previous two numbers in the sequence and this gives you the next number.  So to start with 1+0=1;  1+1=2; 2+1=3; 3+2=5; etc etc.

But how does this get you to the golden ratio?  Well, if you divide one number, by the number before it you get a series of numbers that after a few iterations start to get close to the golden ratio (φ).

Which shows that the number starts to approximate towards the golden ratio with a reasonable level of accuracy after about the fifth iteration or so (well reasonable to a simple engineering brain anyway).. but let's not be blinded by numbers, let's draw an XKCD style graph using our new mathematica code...

The last ImageSize term is important to get a reasonable resolution on the image when you export it from Mathematica for embedding into other documents, but the code above gives the graph below... which I think is quite a good attempt at a XKCD style diagram.

Now that we can determine the Fibonacci sequence and the golden mean easily in Mathematica, we could start to see how these relate to the large sunflower seed heads that mother nature creates time after time...

Just a single line of code will help us generate some nice pretty Golden Ratio inspired spirals in Mathematica which look strangely familiar.

So it turns out that I did know enough about the Fibonacci sequence and the Golden Ratio to be almost dangerous... the trick's going to be can I record a short YouTube video for a maths MOOC as I promised to a half decent standard?  We'll have to wait and see... but now I know I can muck about with formatting diagrams and the code that goes along with the Golden Ratio in Mathematica I can start to mess around with tessalating spheres to create geodesic domes...

And here's a Mathematica graphic after following the procedure set out in this blog post.

But I don't want to go off another tangent just yet with Bucky Fuller... but he was inspired by nature and the cleanness of the geometry that the golden ratio presented.

## Cable-Chains...

Part of the work that I've been undertaking on Mathematica is to create a series of sheets that will calculate the geometry of a cable-chain arch with a set of given parameters.  In part I’m interested in how the cable-chain arch can behave as a deployable structure and looking to build on the work of (Li, Vu, & Richard, 2011) to see how practical a cable-chain structure can be made with regards economy, efficiency, and robustness.  Essentially a cable-chain structure is a curved arch that is sub-divided into straight sections, with cables spanning across the base of two struts as can be seen in the figure below.  Simple versions of these types of structures are widely used for the likes of temporary and deployable aircraft hangers to create large open spans.

Now that I’ve got the makings of a simple Mathematica sheet up and running and I’ve taught myself some rudimentary programming and graphics manipulation skills I’ve managed to start to knock together what I feel are some high quality illustrations for my thesis.

I’ve done this with a mixture of Mathematica to create the base diagram, which I save as a PDF.  I then import the PDF into OmniGraffle to annotate the diagram and then export to a PNG file to maintain the transparent background, this figure I can then host for linking into blogs etc.  Below is a sample figure which shows how the number of segments (nSeg) affects the internal area available for habitation within a typical parabolic arch.

Given that both of my brothers are colour blind and I’ve never done the test, I’m not convinced on my choice of colour schemes, but the good news is that it won’t take long to change if it turns out I’ve made my figures look like something off the set of Austin Powers.

So far I’m finding OmniGraffle quite limited compared to Visio that I’ve been using for my diagrams for perhaps 20 years or so.  I decided to use OmniGraffle though as most of my writing work is done on a Mac, although I also have a PC so I can always create the more complex diagrams on Visio if need be, especially as I’ve managed to get a legitimate copy from work for £12.

I'd love to hear how other engineers and academics approach creating technical figures and sketches on their Macs though, I've a feeling that I'm really missing out on something and there's got to be a much slicker workflow out there.

References:

Li, Y., Vu, K. K., & Richard, J. Y. (2011). Deployable Cable-Chain Structures: Morphology, Structural Response And Robustness Study. Journal for the International Association for Shell and Spatial Structures, 52(168), 83-96.