Matlab_09b

More on Functions

We return now to the script we wrote earlier to export figures (this was in Matlab_07). This can be written as a function as illustrated below - I have called it fancy_export.

The important point here is that I have used if statements with tests to see if the user has supplied arguments, nargin and isempty, to supply default values.

Once you have saved this function in your path (remember the file name must be the same as the function name) you can use it

>> clear all;

>> load matlab_08;

>> return_value = my_graph(m_08);

>> fancy_export([],'jpeg', 'myGraph');

Here is the function in full but it is just a modified version of the script developed in Matlab_07

function return_value = fancy_export(figHandle, fileFormat, fileName)

%

% -----------------------------------------

%

% return_value = fancy_export(figHandle, fileFormat, fileName)

%

% fancy export routine designed to

% save your figures exactly how you

% want them to be

%

% format is one of pdf png jpeg bmp

%

% defaults arguments are gcf, 'pdf' and 'latest_figure'

% -----------------------------------------

% starts here with the basics

% screenSize is approximate

% figSize 10cm by 7.4cm is about right

% for an A4 page and golden ratio

% works for 4 picture formats

% choose between pdf, png, jpeg, bmp

figSize = [12.0 7.4];

screenSize = [37 30];

% now the defaults

if ((nargin<3) || isempty(fileName))

fileName = 'latest_figure';

end

if ((nargin<2) || isempty(fileFormat))

fileFormat = 'pdf';

end

if ((nargin<1) || isempty(figHandle))

figHandle = gcf;

end

% first we set the size units of the figure to

% something familiar

set(figHandle,'PaperUnits', 'centimeters');

set(figHandle,'Units', 'centimeters');

% now sort the size and position out

set(figHandle,'PaperSize', figSize+0.5);

set(figHandle,'PaperPositionMode', 'auto');

set(figHandle,'Position', [screenSize/2-figSize/2 figSize]);

% finally print the picture to a file

print(figHandle, ['-d' fileFormat], [fileName '.' fileFormat]);

end