Wednesday, November 17, 2010

Run matlab m-file in a shell script

It is common to run Matlab without splash and desktop using the following command,
        matlab -nosplash -nodesktop
Sometime the "-nojvm" option also help to reduce the memory requires if the java-virtual-mathine features are not necessary in your script.

But, what should we do if we want to run a Matlab m-file in a shell script? The only thing we need is the option of "-r",

        matlab -nosplash -nodesktop -r YourMFile

However, sometimes it will be much more convenient if we can run the function-type m-file with arguments. Here it comes today's tricky stuff:       
        matlab -nodesktop -nosplash -r YourMFile\(Number,\'character\'\)
Matlab Start Help 

Here is an example,
runMatlabScript.sh

#!/bin/bash
myNum=30
myT="Demo\ of\ Peaks\(${myNum}\)"
myPNG="fig_peaks_${myNum}"
eval "/media/SW_Preload/matlab/bin/matlab -nodesktop -nosplash -r showPeaks\(${myNum},\'${myT}\',\'${myPNG}\'\)"
showPeaks.m:
function showPeaks(myN,myTitle,myPNG)
% show the the peaks
% usage:
%           showPeaks(N,Title,FileName)
%           http://scriptdemo.blogspot.ca

if nargin~=3
   disp('Usage: ')
   disp(' showPeaks(N,Title,FileName) ')
   return
end

hf=figure('visible','off');
set(hf,'color','w','render','zbuffer');
hp=pcolor(peaks(myN));
set(hp,'linestyle','none');
title(myTitle,'fontweight','bold','fontsize',16);
set(gca,'linewidth',2)
eval(['print -dpng -r300 ',myPNG,'.png'])
close;
exit

ShowCalendar