Archive for the ‘matlab’ Category
Back in February I blogged about a little Mathematica demonstration I wrote which plotted several heart shaped algebraic surfaces. One or two people wrote in the comments section asking how to do such plots in MATLAB and I thought that it was about time I came up with the code.
%code to plot a heart shape in MATLAB
%set up mesh
n=100;
x=linspace(-3,3,n);
y=linspace(-3,3,n);
z=linspace(-3,3,n);
[X,Y,Z]=ndgrid(x,y,z);
%Compute function at every point in mesh
F=320 * ((-X.^2 .* Z.^3 -9.*Y.^2.*Z.^3/80) + (X.^2 + 9.* Y.^2/4 + Z.^2-1).^3);
%generate plot
isosurface(F,0)
view([-67.5 2]);
It’s not really the right time of year for hearts though is it? So let’s plot a star instead.

%Code to plot a 3D star in MATLAB
%set up mesh
n=200;
x=linspace(-2,2,n);
y=linspace(-2,2,n);
z=linspace(-2,2,n);
[X,Y,Z]=ndgrid(x,y,z);
%Compute function at every point in mesh
F=X.^2+Y.^2+Z.^2+1000*(X.^2+Y.^2).*(X.^2+Z.^2).*(Y.^2+Z.^2);
%generate plot
isosurface(F,1);
axis off;
view([-48 18]);
For more examples of algebraic surfaces see the Algebraic Surfaces Gallery.
If you double click on a MATLAB .m file on a Windows machine then it will open the file in the MATLAB editor by default. So how do you get similar behaviour in Linux you might ask? This question was recently posed on the MATLAB users group and since no one gave an answer I thought I would have a go and see what I could come up with. After all, how hard could it be?
I’ll cut a long story short and just tell you the solution. To be specific the following tip works on Ubuntu 8.10 running GNOME 2.24.1 but I imagine that a similar procedure would work for some other setups as well.
- Right click on any .m file you like and, in the menu, click on Open With->Open With Other Application
- Click on the arrow to the left of Use a custom command
- In the resulting dialogue box type
matlab -desktop -r "edit %f"
- Click on Open
MATLAB will start up and then the editor will open your file. In future you will not need to type the above command because GNOME will have added an extra item to the Open With menu – namely Open with “matlab”
Hope this helps someone out there and, as always, comments are welcome.
If you enjoyed this article, feel free to click here to subscribe to my RSS Feed.
As more and more people start upgrading to MATLAB 2008b they are uncovering problems with the new Mupad symbolic engine. The latest one was sent to me by Robert in the comments section of my review of the new symbolic toolbox. In the old version of MATLAB (2008a and below) the symbolic toolbox has no problems at all with the following integral
syms x
int((sin(x))^2/x,x)
ans =
1/2*log(x)-1/2*cosint(2*x)
but the new version using the Mupad engine simply cannot do anything with it:
Warning: Explicit integral could not be found.
> In sym.int at 64
Strictly speaking, this isn’t a bug at all but it does expose a limitation of the new system. I have filed an incident report with The Mathworks just in case they are not aware of this issue so hopefully it will be improved in a future version. Thanks to Robert for letting me know about this one.
If you are a user of MATLAB (or any other piece of mathematical software for that matter) then feel free to let me know if you discover any more issues like this. I will always inform the vendor once I have confirmed the problem but I am happy to keep your name to myself if that is what you prefer.
If you enjoyed this article, feel free to click here to subscribe to my RSS Feed.
One comment about my recent review of the new symbolic toolbox for MATLAB 2008b was that I didn’t mention any bugs. To be fair to me I simply didn’t know of any back then but things change so here is one for your viewing pleasure. The following problem with the solve command was originally mentioned on the matlab newsgroup a few days ago.
solve ('x^(5/2) + x^(1/2) = 42')
ans =
0
The solution should have been as follows (found with version 2007b of MATLAB and the symbolic toolbox)
ans =
4.3694949188853387526809476648368
-3.5354997083462823180109844585991-2.6744595794528774961538687374412*i
-3.5354997083462823180109844585991+2.6744595794528774961538687374412*i
Mathworks are aware of the problem and I am sure a fix will be released soon. So why have I chosen to focus on this you may ask?
Well, I have a rather strange relationship with bugs like this in computer algebra software in that I think that they are immeasurably useful! I love finding bugs in programs like MATLAB and Mathematica and will often make as much noise as possible about them. Is this because I hate the likes of Wolfram Research and Mathworks? Do I want to rip into them at every possible opportunity? Do I enjoy seeing big companies fail?
Not even close. Quite the opposite in fact.
Systems such as Mathematica and MATLAB seem almost impossibly powerful – they can do calculations that are far beyond my feeble little mind and they can do plenty of things beyond the ken of much more powerful minds too. It’s very tempting to take whatever results they spit out and present them as the correct answer. Always. All the time. Without exception. Mathematica/MATLAB gives this or that answer so it must be true! Right?
Wrong! So wrong that I go a funny shade of red whenever I see this opinion being expressed. Computer programs are developed by ordinary, everyday people just like you and me. They just happen to be rather good at programming computers. People make mistakes so we should expect that the programs they create will make mistakes too. This is no big deal and is nothing to lose sleep over – it’s just the way things are. I make mistakes, you make mistakes and Shock! Horror! MATLAB makes mistakes too.
Once you know and accept this you simply factor it into the way you work. When you plug a problem into Mathematica or MATLAB make sure that you think about the result you expect to get. Does the output look reasonable or is it clearly a load of old hogwash? If it does look reasonable then can you compute it via another method to check that there is nothing wrong with the first algorithm you tried?
How much does the correct result matter? If it is a matter of life and death then check it again and again. Then once more just for good measure. If it doesn’t matter so much then maybe check it just the once – or maybe not at all if it’s no big deal. Just be aware that it might be wrong.
There is no need to be too concerned though since one of the reasons why bugs like the one above are so interesting is that they are actually quite rare. I can sit in front of MATLAB day after day and never uncover a single bug – it’s pretty good at what it does to be fair. So…you can safely trust MATLAB – most of the time at least :)
I think that the occasional bug or two is good for the soul as they remind us that nothing is infallible – not even programs like MATLAB and it’s almost a shame that The Mathworks fixes them so quickly. So…go forth and find bugs. Don’t be afraid of them but learn from them. When you do find one, please tell me all about it though as I love a good bug! It’s probably best to tell the vendor about it too though, after all they are the ones who can fix it.
Finally, if anyone from The Mathworks or Wolfram Research is reading this, then I have a request if I may. Take a look through your bug database and try to pick out a really juicy one for us. It could be a symbolic integral that your system couldn’t do or maybe a numerical result that is so far from being correct it’s not even funny. Why did your program fail with that particular problem? If it is a straightforward programming bug then it’s probably not very interesting to the general reader but if there is something tricky about the mathematics that you had to overcome then I bet there will be a lot of people who would be interested in hearing about it.
Me for one!
If you enjoyed this article, feel free to click here to subscribe to my RSS Feed.
Introduction
Just over a couple of weeks ago, The Mathworks released the latest version of their main product, MATLAB 2008b, which includes a completely new version of their Symbolic Toolbox. If you are new to MATLAB then maybe a quick explanation is in order here. The base MATLAB package is strictly numerical and has no support for the symbolic manipulation of equations. For example, if you want to solve the quadratic equation x^2 -2*x -5=0 numerically then basic MATLAB can help you. The syntax may look at bit minging at first sight but it does the job and does it efficiently.
roots([1 -2 -5])
ans =
3.4495
-1.4495
If, on the other hand, you wanted to solve the general quadratic a*x^2+b*x+c=0 in terms of a,b and c then you are out of luck using MATLAB on its own. With the symbolic toolbox, however, calculations such as this are trivial thanks to the solve command
syms a b c x;
y=solve(a*x^2 +b*x+c)
y =
-(b + (b^2 – 4*a*c)^(1/2))/(2*a)
-(b – (b^2 – 4*a*c)^(1/2))/(2*a)
It will also give the answer to our first quadratic exactly – which is nice.
solve('x^2 -2*x -5=0')
ans =
1 – 6^(1/2)
6^(1/2) + 1
It even has the power to evaluate integrals symbolically – something that I wish I had access to when I was in high school. It misses off the constant of integration but this is the standard behaviour for almost all symbolic integrators and so isn’t anything to worry about. (Note to teachers: If you have a student who always gets the integral correct but shows no working and never includes the constant of integration – now you know why). A simple example:
int('cos(x)^2')
ans =
x/2 + sin(2*x)/4
So how are these symbolic feats achieved you may ask? Well, it’s all a bit of a trick really because MATLAB isn’t doing any of the work itself. What it does is send the problem to another program called MuPad. Mupad solves the problem and sends the result back to MATLAB for display. Think of it as mathematical out-sourcing if you will – a bit like copying your friend’s calculus homework. This is all done seamlessly behind the scenes and so, as far as the user is concerned, the symbolic toolbox simply adds a range of new commands to MATLAB that can do symbolic calculations. It doesn’t matter that MuPad is really doing the work. Does it?
Yes it does! You see, it wasn’t always MuPad that did MATLAB’s symbolic homework for it. In older versions of the Symbolic Toolbox (2008a and earlier) it was a completely different application that did the symbolic grunt work on MATLAB’s behalf, namely Maple. For some reason, known only to Maplesoft and Mathworks, Maple was dropped from the symbolic toolbox in favour of the lesser-known MuPad. The Mathworks then went and bought the company that produced MuPad and now the only way you can buy a copy of Mupad is to buy MATLAB together with the symbolic toolbox.
So, this new incarnation of the Symbolic Toolbox for MATLAB may look the same as the old version but it has had a brain transplant and thus has a completely different personality with a different set of abilities and behaviours. When I first heard about this change I was very worried – I’ve seen this before you see.
Another mathematical application, MathCAD, also used to use Maple as it’s symbolic engine and it dropped it in favour of MuPad when version 14 was released back in early 2007. It wasn’t pretty! I support MathCAD at the University of Manchester in the UK and all of a sudden people’s symbolic calculations weren’t working as they expected. Lecture notes needed to be rewritten, code needed to be modified and I spent ages scratching my head trying to work out where all the differences were. Some were…interesting…to say the least.
I also support MATLAB at Manchester and we have a LOT more MATLAB users than MathCAD users. Orders of magnitude more in fact and so this transition from Maple to Mupad in the symbolic toolbox was giving me sleepless nights. How much was it going to change things? How different is the input syntax from before? What differences in functionality can I expect to see? Is it any better or worse than before? Most importantly, how much work is it going to generate for me and my colleagues.
Same input, different output
I was very relieved to see that most of the input syntax hasn’t changed at all from older versions of the toolbox. What has changed, however, is the output. Lets look at our simple quadratic example again. In both 2008a and 2008b the input syntax is
syms a b c x;
y=solve(a*x^2 +b*x+c)
In an old version of the symbolic toolbox (specifically 2008a) the output from these commands is
y =
-1/2*(b-(b^2-4*a*c)^(1/2))/a
-1/2*(b+(b^2-4*a*c)^(1/2))/a
In the new version (2008b) we get
y =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
Of course these solutions are mathematically equivalent but they are written in rather different ways. It’s worth pointing out that this isn’t an isolated case – almost every symbolic calculation I tried gave subtly different output like this. Not incorrect I hasten to add – just different. Also, notice that 2008b has given the roots in a different order to 2008a. Most of the time this will not matter but if you have written code that assumes a certain order (and doesn’t check) then you might be in trouble. Of course writing code in such a manner is a bad idea anyway but I like to cover all bases when thinking of possible support issues.
More examples:
syms a b
b=a/3
2008a:1/3*a
2008b:a/3
syms x y
[x,y]=solve('x^2+y^2=1','x^3-y^3=1')
In 2008a:
x =
0
1
-1+1/2*i*2^(1/2)
-1-1/2*i*2^(1/2)
y =
-1
0
1+1/2*i*2^(1/2)
1-1/2*i*2^(1/2)
in 2008b:
x =
1
0
(2^(1/2)*i)/2 - 1
- (2^(1/2)*i)/2 - 1
y =
0
-1
(2^(1/2)*i)/2 + 1
1 – (2^(1/2)*i)/2
Practical upshot: If you have written a MATLAB book or a MATLAB lecture course and you have included printouts of the output then you have some minor updating to do. If you have written code that assumes a certain solution order then you have some programming to do.
Variable precision arithmetic
With plain vanilla MATLAB you are limited to, at best, double precision arithmetic. This is screamingly fast since it is directly supported by the hardware of your computer but for some problems you simply need more precision. This is where variable precision arithmetic (vpa) comes in handy, allowing you to calculate to as many decimal places as your computer can handle at the expense of computational speed. The new version of vpa seems to work in exactly the same way as the old one:
digits(50)
vpa(pi)
vpa('(1+sqrt(5))/2')
3.1415926535897932384626433832795028841971693993751
1.6180339887498948482045868343656381177203091798058
Calculus
The first real problem I ever asked a computer algebra system to do for me was an indefinite integral that took me ages to work out by hand. The fact that I got the correct answer in just a few seconds completely entranced me and I have been throwing integrals at such programs ever since. These days I am much more interested by integrals that computer programs fail to do rather than the ones they do with ease. It’s even more fun when the integral turns out to be trivial to do by hand.
Unfortunately for Mathworks, this new symbolic toolbox has given me a few more ‘interesting’ examples to think about. Here are a couple of integrals that the old toolbox could do but the new one can’t – both of which come from an introductory MATLAB textbook (which now needs a 3rd edition by the looks of things).
int('arctan(x)/x^(3/2)',0,1)
2008a: -1/2*pi+2^(1/2)*log(2+2^(1/2))-1/2*2^(1/2)*log(2)+1/2*2^(1/2)*pi
2008b: Warning: Explicit integral could not be found.
simplify(int('sqrt(1+cos(x)^2)'))
2008a:-csgn(sin(x))*EllipticE(cos(x),i)
2008b: Warning: Explicit integral could not be found.
There are probably more but I haven’t had much of a poke around so if anyone comes across any more of these, please let me know via the comments and I’ll do some follow up posts. Obviously, I’d also like to know of any integrals that 2008b can do which elude 2008a – I just haven’t found any myself yet.
Of course, just like the old symbolic toolbox, this new one has no problem with differentiation and here is a simple example for the sake of completeness.
diff('tan(x)')
2008a:1+tan(x)^2
2008b:tan(x)^2 + 1
More examples of symbolic functionality.
If you have never seen the symbolic toolbox in action before then here are a few more examples of what it can do – with output from both this new kernel and the old one.
Factor a large integer into its prime factors.
factor(sym('567836543898634'))
2008a: (2)*(37)*(347)*(4804201)*(4603)
2008b: 2*37*347*4603*4804201
Solve an Ordinary Differential Equation symbolically
dsolve('D2y = -a^2*y', 'y(0) = 1', 'Dy(pi/a) = 0')
2008a: cos(a*t)
2008b: cos(a*t)
Find the determinant of a symbolic matrix
m = sym('[d^2 2 7; d d^3 9; 1 5 1/5]');
det(m)
2008a:1/5*d^5-45*d^2+173/5*d+18-7*d^3
2008b:d^5/5 – 7*d^3 – 45*d^2 + (173*d)/5 + 18
You get the idea – this is a useful toolbox – no matter which version you are using!
Talking to the Mupad kernel directly
The commands provided by the symbolic toolbox represent just a tiny fraction of what MuPad is capable of and so The Mathworks have added some commands to the 2008b symbolic toolbox to allow you to talk directly to the MuPad kernel. As long as the command you are sending produces a non-graphical output then you are good to go:
You can evaluate a Mupad command from the MATLAB command line by using the evalin command which uses the following syntax.
y = evalin(symengine,'MuPAD_Expression');
As a specific example – let’s calculate the number of partitions of 100 in MATLAB using Mupad’s combinat::partitions command:
y = evalin(symengine,'combinat::partitions(100)')
y =
190569292
I think this is just fabulous as it means that the symbolic toolbox adds an immense amount of functionality to MATLAB. This is a major advance compared to the old version of the symbolic toolbx which only provided direct access to a subset of the underlying Maple computational kernel. If you wanted access to all (non-graphical) Maple functionality from within MATLAB then you needed to buy a rather expensive toolbox called the Extended Symbolic Toolbox. As of version 2008b this extended toolbox no longer exists since the standard symbolic toolbox contains the full version of MuPad. Advanced symbolics from MATLAB just got a whole lot cheaper!
So much syntax, so little time
Having access to the full functionality of Mupad from MATLAB is wonderful but it comes at a price – you have to learn a whole new set of syntax rules. Let’s look at some examples
MATLAB - acos MUPAD - arccos
MATLAB - besselj MUPAD - besselJ
MATLAB - conj MUPAD - conjugate
In MATLAB you suppress output with a ; but in Mupad you use a :
In MATLAB you list all used variables with the whos command. In Mupad it’s anames(All, User)
You get the idea…Of course this is to be expected since Mupad and MATLAB are two completely different systems but these syntax differences really show up the fact that the symbolic toolbox is simply just a set of glue and bolts holding together two different products. Maybe now that Mathworks have bought Mupad outright these differences will start to go away and Mupad will become much better integrated with MATLAB in the future.
For a more detailed list of the syntax differences see this article from Mathworks – Mupad for MATLAB users.
Of course the people I really worry about are those who have written a lot of code using the Maple syntax of the old toolboxes (both standard and extended). They now face a choice – never upgrade, rewrite their code from the ground up or find another way of hooking into the Maple kernel.
Choose your engine
If you have a full copy of Maple installed on your machine then one option open to you is to type
symengine into MATLAB which will reward you with a dialogue box allowing you to switch from the Mupad engine to the Maple engine. Obviously you cannot do this if you do not have a copy of Maple installed.
At the moment I am unsure which versions of Maple are compatible with this option and I couldn’t find a definitive list on Maple’s website but I guess that will become clear in time. Alternatively you may choose to use Maplesoft’s new product – The Maple toolbox for MATLAB – but from what I can tell that isn’t fully backwards compatible with the old symbolic toolboxes either.
Something I am unsure of at the moment is whether or not you could get the 2008b symbolic toolbox to use the Maple kernel from an older version of the toolbox should you have one lying around. Expect to see an update on this question soon.
Bonus! Full version of Mupad!
While the old version of the symbolic toolbox for MATLAB only had access to a limited number of Maple functions, this new version contains everything in Mupad and when I say everything I really mean it. Type mupad into MATLAB and you are rewarded with nothing less than the full version of Mupad 5.1 – exactly as if you had installed it as normal and started it from the Windows start menu.
It’s all there…programming, graphics – the lot. This is great news for MATLAB users but probably not such good news for old time Mupad users because if they want to upgrade to the latest version of Mupad then they need to buy both MATLAB and the Symbolic Toolbox – a combination that is more expensive than Mupad on it’s own used to be.
There is so much great stuff in Mupad, an application I had never used before until now, that this review almost didn’t get written because I was having too much fun playing.
Summary
So..this update of the symbolic toolbox for MATLAB is a biggie and no mistake! Thanks to the Maple->Mupad brain transplant it is a completely different product and I sometimes find myself wondering if it should have been given a totally different name from ‘symbolic toolbox’ to reflect this.
On the whole, I like it. It’s probably going to cause me a world of pain when I am asked to help people migrate from the old version but I am hopeful that it’ll be worth it in the long run. Here’s the executive summary
- The majority of the input syntax for the symbolic toolbox ‘wrapper’ commands such as syms, int and diff is identical to older versions.
- The output given by these commands is different from the old version in almost every case. The differences range from simple re-arrangements through to completely different evaluations.
- The actual symbolic work is now done by Mupad. In the past it was done by Maple.
- The new toolbox seems to be weaker at integral calculus than the old one but I cheerfully admit that I haven’t exactly gone into detail on this.
- The Extended Symbolic Toolbox is no more. If you need full access to Maple commands then you need to buy the full version of Maple.
- You get the full version of Mupad included with the new symbolic toolbox. Just type mupad at the MATLAB command prompt to launch it.
- The only way of buying Mupad these days is to buy MATLAB and the symbolic toolbox.
Finally – since I mentioned my job in this review I would like to make the usual disclaimer. This article (and indeed this blog) has nothing to do with my employer, The University of Manchester. All opinions are mine and mine alone – not theirs.
If you enjoyed this article, feel free to click here to subscribe to my RSS Feed.
There have been loads of mathematical software releases recently and here is another – version 3.03 of Octave – the free, open-source MATLAB like maths package. No major new features this time as it is essentially a bug fix release.
The Mathworks released the latest version of their flagship product, MATLAB 2008b, on October 9th. Along with the usual wide range of incremental improvements, there are one or two major changes such as a complete overhaul of the symbolic toolbox and a new Econometrics toolbox.
Other posts you may be interested in.
Review of the new Symbolic Toolbox in MATLAB 2008b
So..I finally get hold of a standalone copy of MATLAB 2008a and set about installing it on my Ubuntu laptop. I have installed MATLAB literally hundreds (if not thousands) of times so this is going to be easy. Right? Wrong!
I am using the installation DVD which is mounted at /media/cdrom0 so I type the following into the bash command prompt:
/media/cdrom0/install
bash: /media/cdrom0/install: /bin/sh: bad interpreter: Permission denied
gah! OK, no problem – I’ve seen this before so I type
sh /media/cdrom0/install
-------------------------------------------------------------------
An error status was returned by the program 'xsetup',
the X Window System version of 'install'. The following
messages were written to standard error:
/media/cdrom0/update/install/main.sh: 178:
/media/cdrom0/update/bin/glnx86/xsetup: Permission denied
Attempt to fix the problem and try again. If X is not available
or 'xsetup' cannot be made to work then try the terminal
version of 'install' using the command:
install* -t or INSTALL* -t
-------------------------------------------------------------------
Sorry! Setup aborted . . .
Permission denied? Ahh, I should have used sudo – silly me. After all, if I don’t then I am going to run into trouble eventually. So I try
sudo sh /media/cdrom0/install
Same result as before it seems. Let’s try the suggestion given by the install script and run the text only installer:
sudo sh /media/cdrom0/install* -t
I get asked if I want to agree to the license agreement before getting this error:
/media/cdrom0/update/install/main.sh: 582: /media/cdrom0/update/bin/glnx86/xsetup: Permission denied
Before I rolled my sleeves up and got my hands really dirty I did some googling. This link offers some advice – unmount and remount the DVD as follows:
sudo umount /media/cdrom0
sudo mount -o exec,suid /dev/scd0 /media/cdrom0
then run the installer again:
sudo sh /media/cdrom0/install
Success! Hope it worked for you too :)
I now have access to a standalone copy of MATLAB along with a whole slew of toolboxes. This means that I can play with MATLAB on my many many train journeys so expect to see a lot more MATLAB-centric content here soon :)
I’ve linked to Blinkdagger a few times before because they write great introductory tutorials on how to use MATLAB in various fields. Their latest one, written by Rob Slazas, takes a look at how you can use some of the functions in the MATLAB statistics toolbox to test a hypothesis.
I freely admit to knowing nothing about this subject so couldn’t possibly comment on the technical accuracy of the post (although I would imagine that it’s just fine) but it certainly looks like a nice place to start. Head on over to blinkdagger to take a look.
