Saturday, May 24, 2008

External commands in MATLAB

For some time now, I have often wondered why MATLAB highlighted text starting with a ! in a different colour. I thought nothing of it until recently when I was, as always, randomly entering code into MATLAB and had accidentally put a exclamation mark in the command window (I can't remember the exact reason why I was using exclamation marks). The result was quite interesting: it sent the command to the command interpreter outside of MATLAB which, of course, flagged this as an error. In seeing this, I stopped what I was doing and started to play about with this newly discovered shortcut.


My first command was !bash which, being in Linux, should run the BASH shell... which it did. I could then use MATLAB as a glorified terminal window. Whilst in BASH, I decided to check for updates for the machine which would require me to use sudo followed by the update command (and as I use Ubuntu, that's simply turns out to be sudo apt-get update). As always (with the exception of doing this in MATLAB), I was prompted for my password. Interestingly, MATLAB behaved like the terminal window and didn't display my password which normally happens should one Telnet their POP3 server (a hobby of mine). I guess this would be due to a so-called seamless "pipe" between MATLAB and, in this case, BASH.


From here, one can then go a step further an build m-files that run external commands. Of course, there's the issue of platform dependency here (mainly for the UNIX group) but one can work around this issue. A nice feature (at least in the UNIX version) is the fact that ! commands run in the current working directory (try !pwd and await a response) which means navigation isn't a problem. One minor niggle that I haven't been able to resolve just yet is trying to take a result from the external command without resulting to taking output manually using the command > output.log method.


So let's create something that works out what platform we're running on from within MATLAB and obtains the flavour of Linux using Linux command uname



if isunix

% In Unix, determine OS type

!uname -s > unixname.txt

% Now read this file:

fid = fopen(unixname.txt, 'rt');

if feof(fid) == 0 % Determine if at end of file

osname = fgetl(fid); % Get line

else

disp('File ended early');

end

elseif ispc

disp('I''m in MS Windows');

else

disp('Impossible: You''re not running either Windows or UNIX?');

end


Hopefully you are able to see the potential here in executing external applications based on what operating system environment is currently being used. Both Windows and UNIX support the command > output.log method (which you may remember from the Queue system). In fact, I frequently create script files using a combination of echo and the "append" verb >> where I can get away with it.


Read more on this article...

Sunday, May 11, 2008

LaTeX in MATLAB

Not too long ago, I was entering random commands into MATLAB (read: I was bored, so wondered if certain commands existed). I finally came across a few "games" which would have a practical side to them:


  • xpbombs for a Minesweeper equivalent

  • fifteen for a puzzle game

  • sf_tictacflow for naughts and crosses/Tic-Tac-Toe

  • sf_tetris for Tetris



It was after this search, I wondered into the LaTeX command which was cunningly called latex. This command makes it possible to port equations and matrices from the MATLAB workspace to your LaTeX document.


The latex command makes use of the Symbolic Toolbox which is available with MATLAB (providing you have the appropriate licence). The Symbolic Toolbox can easily calculate integrals and Taylor expansions algebraically (however it doesn't show workings if you're looking for the intermediate steps). It can even convert matrices and vectors into LaTeX providing you convert the matrix or vector into a symbolic object first.


To convert an ordinary double object into symbolic object, one simply has to encapsulate the double object in a sym environment, i.e. output = sym(x). The outputted object can then be processed for LaTeX conversion using the latex(output). In the case of matrices, the output even puts the dynamic brackets that resize depending on its contents (i.e. the \left[ and \right]) which, of course, can be changed to whatever you want once its imported into your document.


Taylor expansions? No problem. Simply assign a variable like x to be symbolic by either typing syms x or x = sym('x'), then output = taylor(exp(x)) should you wish to see the Taylor expansion of e^x. As before, LaTeX-ify the output by using latex(output) which you can then copy into your document.


If copy and pasting is getting a little too much, you could use the inbuilt copy command which will move the output into clipboard for you. All you'll have to do then is paste the contents of clipboard into the application of your choice. Easy. Here's the code: clipboard('copy', latex(output)).


What obviously comes next is a quick script that does this all for you depending on the input. Like many of my scripts, I simply append the word "it" to the original function name; so in this case I created a latexit.m file:


function output = latexit(input, copyToClipboard)



output = [];



if nargin == 1

copyToClipboard = true;

elseif ~islogical(copyToClipboard)

warning('Second argument should be logical. Assuming value is false');

copyToClipboard = false;

end



if isa(input, 'sym')

% Symbolic object

output = latex(input);

else

% Another type of object

try

output = latex(sym(input));

catch

error('Could not process input. Try converting object to a symbolic form manually and then reprocess');

end

end



if copyToClipboard

clipboard('copy', output);

end


That should be it. A script file that could convert matrices and output them as LaTeX in addition to moving the LaTeX code into the clipboard (which can be disabled by supplying false as the second argument). If you were really lazy, you could wrap the LaTeX code in an equation environment too, but there's little point in doing that here.


Further investigation into how this works reveals that it goes deeper than the Symbolic Toolbox as it turns out it uses the Maple engine to turn the symbolic object into LaTeX output. Why reinvent the wheel when someone's already done a fine job?


Read more on this article...

Tuesday, May 6, 2008

Linux, Compiz and MATLAB

Recently, a new version of Ubuntu was released and, being an Ubuntu user, I installed this latest version. For some time now, I've not been able to run MATLAB with the fancy window graphics switched on without displaying an almost blank (grey) screen. That is until finding a helpful post on the Ubuntu Forums.


For those that don't know, the "fancy window graphics" within Ubuntu and, from what I gather, other distributions of Linux are produced by a component known as Compiz which is capable of producing many interesting effects such as water ripples, a desktop cube plus many more effects.


The reason why MATLAB displays a grey box when Compiz is enabled is down to the way Java attempts to interact with window managers. According to one post I read, the problem arises due to the Java toolkit code assuming that all window managers re-parent windows. If a window manager (such as Compiz, Compiz Fusion, etc.) is running, then the Java toolkit waits for new windows to be re-parented before it starts handling certain events on them. Since Compiz and other window managers do not re-parent windows, the Java-based applications end up waiting forever.


There was a time, a year or two ago, where the fix consisted of altering the Java source which was awfully messy and didn't work for every distribution of Linux. This time, there's a better workaround which doesn't involve the AWT_TOOLKIT patch (which I, personally, could never get working). This one is a simple and makes use of the latest version of Sun's Java (as Sun eventually got around to patching this problem). MATLAB, by default, is shipped with its own Java Virtual Machine (JVM) and so is independent of the version that exists (or doesn't exist) on your workstation. We therefore have to override this information by typing in the following within the Terminal:


export MATLAB_JAVA=/usr/lib/jvm/java-6-sun/jre/


This code simply exports the variable MATLAB_JAVA where it then exists for the lifespan of the Terminal window. Note that you should replace the path I've used to the latest Sun version of the Java Runtime suite.


From here, one can type in matlab -desktop or, simply, matlab (I am the proud owner of a broken installation which requires me to enter the -desktop argument). Typing this in every time you want to open up MATLAB could be described as arduous, so the creation of a script file that could do this for you sounds quite enticing.


If, like me, you enjoy creating random scripts that do numerous things (like connect via SSH with key authentication), you would probably have a folder where you store all your scripts. If not, it's not too early to start: create a new folder within your home folder by typing mkdir bin. If you're lucky, this should be added automatically to your $PATH variable for you (as it's defined within your .profile within your home directory. Next, type in cd bin where bin is the location to your script files. From the top of your head, think of a name to call MATLAB which will load everything for you; I'll pick matlabgo. Once you've decided, continue and replace matlabgo with the name of your choice. Type:


echo "export MATLAB_JAVA=/usr/lib/jvm/java-6-sun/jre/" > matlabgo

echo "matlab -desktop" >> matlabgo

chmod u+x matlabgo


So we've basically created the file (without use of any editor, mind you) and then changed the permissions of our link so that we can execute (and, hence, use) it. You should now be able to type in matlabgo into the Terminal and even link up shortcuts that use this script file.


For those that are interested in my source, head to: http://ubuntuforums.org/showthread.php?t=635142 for more information.


Read more on this article...