# Tag Archives: Mathematica

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.

General

## Speed...

I'd never really given speed a lot of thought when coding my Mathematica notebooks, but after recently attending a seminar I think it's something I need to spend some time thinking about.  My sheets are normally fairly trivial in comparison to some of the large banking house notebooks that run, but what I was interested to hear was that some of the sheets being run take over 6 hours from the other delegates.  That's a long time to wait to see if your numbers are rubbish.

Also what was interesting was that the presenter spends a lot of his time making other people's code work faster, essentially that's the core of his consultancy business.  Some speed improvements were up to 912% faster.

So a 6 hour sheets would potentially run in less than 30 seconds.  Which is a hell of a lot faster and lets you run various scenarios in a day rather than one a day.

One simple thing that I took away from all of this is if I'm only interested in numerical results rather than symbolic, then I need to think carefully about the level of precision I require.

For example using the /AbsoluteTiming flag you can do a simple test to see the difference that the level of precision makes.  By simply adding a decimal point to the number 2 it will convert to machine level precision.

Gives a timing of 0.283438 seconds on my machine.  Simply adding a decimal place to the number 2 gives a significant speed jump.

Gives a timing of 0.000293 seconds, which is a massive shift in computation time.

Something to consider.

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

## 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.

## 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.

Teaching

## Code...

I'm spending a lot of my time tinkering in Mathematica lately, with two objectives really.

1.) I want to write some code to calculate the tedious geometrical aspects for me for my research.

2.) I think that Mathematica has some real potential for students who are trying to learn structures, particularly through the CDF files.

I've learned various programming languages over the years most of which I've taught myself, admittedly not to the level that perhaps a computer programmer would, but I've armed myself with just enough knowledge to be dangerous and get the task done that I want to achieve.  I've created countless spreadsheets that can do all sorts of elaborate calculations and also to use as validation calculations for more complex analysis models that I've created.

This is a skill that I take for granted for engineers, particularly of my age, and in most engineers that are a couple of years older or so I tend to find that they've spent some time abusing Fortran code in some fashion.  Fortran isn't a language that I've ever learned, but it's probably one of those languages that a lot of engineers have dabbled with at some point.

One trend I've noticed in a lot of younger engineers is a reluctance to create computer code and indeed even in creating what I would consider simple spreadsheets to make a calculation tool that can run several scenarios for them and validate an approach to determine the boundaries of their calculations.  Increasingly there seems to be a preponderancy for young engineers to select their FEM weapon of choice and throw triangles at it until the model begs for mercy, or to download an app that some other bright spark has written to do at least part of the process of what they want to happen.  None of this promotes a deeper understanding of how the process works though unfortunately.

Perhaps the days of writing your own code are long gone for young engineers? But part of me thinks that they are missing out on a real opportunity to structure their understanding of the steps needed to do certain tasks as they assemble their code.  Writing code to perform a task, whether on a spreadsheet or in a more formal programming language, is a great way to develop understanding and to explore the intricacies of design codes and I feel that younger engineers are missing out on this experience by only using off the shelf packages.

One encouraging aspect is that with the launch of the Raspberry Pi I can see that if this continues to gather momentum that younger generations will again an ability to tinker and break programming code and gain an appreciation of the advantages that breaking down engineering problems into a series of procedural steps can bring.

At least for the next year or so I'm still responsible for sculpting young engineers minds and I'm determined to develop a fun way of getting them to extend their understanding of how to write code or spreadsheets, I just need to work out a way of doing this within the confines of the resources I do or don't have available.

What do you think? Should engineers know how to programme or at least be able to create simple spreadsheets?

## 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.

## Kriss Kross...

I've been really busy with various things associated with my new house lately and not really had much time to tinker and meddle with Mathematica or my PhD.  One of the key elements that I need to investigate is to calculate the internal area of a polygon where cables cross...  This will vary, depending on how many internal cables that I have and so I need a quick way of finding out the internal area for lots of different permutations.

This is a simple polygon problem which can be easily calculated once you know the cartesian co-ordinates for each of the key points using the following equation which is presented for the general condition.  It's not a hard calculation, as really it's just triangles, but it is a tedious calculation, which means it's perfect for Mathematica or Excel.

However, the tricky part comes from determining where the cables actually cross over as that is where the cartesian co-ordinates will come from that are needed to determine the areas.  The calculation of the co-ordinates can be done a few different ways, but I've decided to solve the problem through using some vector based geometry, consider the simple condition below which is just for two lines that cross, how do we find the point where the lines intersect?

You could describe the two lines in the general term of y=mx+c, but this isn't what I want to do within Mathematica as I want to automate this for a wide range of values and lines and so iterative geometry using vectors is likely to be far more beneficial.  Representing these two lines in vector format using cartesian co-ordinates gives:

Now we know the equations in vector format it becomes possible to solve both of these equations to determine λ and μ which when back substituted into either equation will give us the co-ordinate for the intersection point p5 in (x,y) format.

This isn't that difficult to do by hand, but requires a bit of vector manipulation to expand the brackets and given my low attention span I would inevitably get it wrong after a few run throughs, but in Mathematica the problem gets much more simple, so for the example below we'll assume that the four co-ordinates are at 4m away from the origin (0,0) that is point p1.

{p1, p2, p3, p4} := {{0, 0}, {4, 4}, {0, 4}, {4, 0}};

Solve[{(1 - λ) p1 + λ*p2 == (1 - μ) p3 + μ*p4}, {λ, μ}, Reals];

p5 = Flatten[(1 - λ) p1 + λ*p2 /. %]

Executing this codes gives the intersection as being at point (2,2) in a fraction of a second, which is where you would expect it to be.  Now to explain the three lines of code and what they do, I'm sure a more experienced user could make this code much neater but doing it this way makes sense to my tiny brain.

The first line simply sets the variables p1-p4 with their corresponding cartesian co-ordinate position, giving the point two in the top right corner 4m up and 4m across, p3 is along the bottom 4m away, p4 is straight up in the top left corner 4m above point p1, as shown in the figure below.

The second line then solves the two vector equations of the lines for λ and μ and makes sure that they are real numbers, rather than imaginary.  The real part probably isn't necessary, but it's just a force of habit that I put this in when using the solver as a just incase.

The final line substitutes the λ value back into the equation and then stores this as variable p5 so that I can use this in up and coming calculations, this was the fiddly part for me and makes use of the strange /. % input that allows the equation to effectively go back and substitute the solutions from the Solve command into the equation specified and recalculate and because my equation has the λ within it Mathematica knows this is what I want substituting in even without me being explicit.   I spent ages trying to work out this final stage, but now I've cracked it as a principle I can start to roll it out on the other sheets that I've been working on and this was the reason for writing this post incase it too helps someone else.  Now I can directly write the solution outputs from Solve, FindRoot, and NSolve and then carry on using these within my calculations rather than having to manually type them in.

This process lets me know that the intersection point is at (2,2) and now I know that the process works I can start to extrapolate this algebraically for the general conditions and start to calculate the areas of my polygons.

All of the figures in this post have been written using OmniGraffle, which I'm slowly getting to grips with, I can't make it dance as well as I can Visio, but I think it will help create some nice looking diagrams for my thesis once I get more proficient with it.

General

## Summer loving...

Well, having completed my first complete academic year, I'm now entering into semester 3 and I need to start planning what it is that I want to achieve over the summer whilst most of the students are away.  There's a common misconception it would appear, that academics all bugger off to Tuscany for the summer running care free and naked through the hills with the wind blowing through their hair, finally returning in September to teach again.

The truth of the matter is that this is perhaps the only time in the year when we can actually get stuff done that we want to, we've access to the laboratory and we're able to crank through all of those things that we've just not had opportunity to get round to through the academic year due to other pressures.  The key to getting things done though is to create a list of what it is that you want to achieve... so here's my list (in no particular order yet as I need to put timescales next to them).

• Review COMSOL and attend a training session.
• Develop a series of Mathematica sheets for calculating geometry.
• Learn ANSYS.
• Learn Inventor.
• Update lecture materials for the MSc and some of the first year modules.
• Write 2 chapters for my PhD.
• Complete my Lynda.com training session for Blackboard 9.1.
• Completely re-populate all of my Blackboard area, embedding Mathematica.
• Complete WriteTEL2 programme with Napier.
• Write resit papers and mark any resubmissions from repeating students.
• Obtain ethics approval for my innovative structures teaching programme.
• Finish two journal papers.
• Become registered as a STEM ambassador.
• Complete a 'Meet the Engineer' session at MOSI.
• Arrange next year's Technical Lecture Programme for the IStructE
• Complete my examination marking for the IStructE
• Complete the Advanced Structural Behaviour Exam paper for the IStructE.
• Submit draft textbook outline to McGraw Hill.
• Define a solid workflow for creating technical illustrations, MS Visio or Adobe Illustrator.
• Explore Wolfram SystemModeller.
• Find and create a pool of study buddies...

In amongst this I've also a significant build on with our new house, although we've a good builder on board so hopefully it shouldn't drain too much of my time.  I also intend to take some time out for a holiday, as well as doing some hill walking with a little landscape photography thrown in too.... but here's the rub... when I look at the list above I find myself thinking that's quite a lot of stuff to fit in through the summer months, but the difference being that actually I find the activities listed above good fun and I've actively taken on board these activities through my own volition... they're not crap that has been dumped on me by an inconsiderate boss.

This ability to be highly self-indulgent is perhaps the thing I like the most having joined academia, although I still feel guilty come every Friday when I've not completed a timesheet... but just to be able to make time in my own diary to head off and read about something I find interesting is incredibly liberating...