wiki:FAQ_MatlabPlots

How do I display Matlab plots as a result?

The first step is to save the graph as a png image. The Matlab / Octave example below shows how to do this using the print function and the -dpng flag:

%% test.m

% A function of two variables, described in Matlab help.
% The output is 20x20 matrix of Z values

isOctave= exist('OCTAVE_VERSION');
fname='tst';
fff=peaks(20);  
mesh(fff);                   % Test figure shown for adjustment

% Flush pending graphics events
drawnow;

% this command saves the graph as a png file
eval(sprintf('print -dpng %s.png',fname));

In Matlab, it is suggested that you avoid using the -nodisplay flag when dealing with graphics and use the -nojvm -nosplash command line combination. The -nodisplay command line flag will prevent the figure from being displayed, but also encourages Matlab to segfault and hand you back massive traceback. The -nojvm -nosplash command line flag combination does a good enough job at keeping graphical user interfaces from popping up. Additionally you can set the figure's visibile property to off as shown in the example below. A more Matlab-centric example follows:

fname='tst.jpg';

% create our figure
fff=peaks(20);
mesh(fff);

% turn off the visibility of the current figure
set(gcf,'Visible','off');

% save the current figure to fname
saveas(gcf,fname);

% close the current figure
close(gcf);

Once you have a png or jpg file, you will need to put it into the your Rappture Library. using the rpLibPutFile function. The rpLibPutFile command will automatically compress and base64 encode the image file and place it into the Rappture Library.

Check out these pages for more information on placing base64 encoded data into image and structure nodes.

lib = rpLib(infile);
rpLibPutFile(lib, 'output.image(peaks).current', 'tst.png', 1, 0);
rpLibPutString(lib, 'output.image(peaks).about.label', 'peaks Graph', 0);

If a wrapper script calls the matlab script, the base64 encoding can be done inside the wrapper script. Tcl and Python have special modules to deal with image conversions.

Here's an example of converting a tiff image to base64 encoding in Python:

#!/usr/bin/env python

import base64, Rappture
from PIL import Image
xmlfile = "driverNNNN.xml"
lib = Rappture.library(xmlfile)
if isinstance(lib,Rappture.library):
    im_tiff=Image.open("image.tiff")
    if im_tiff:
        im_tiff.save("image.jpg")
        im_jpeg=open("image.jpg",'r')

        # generate MIME data from image
        jpgMIMEdata = base64.encodestring(im_jpeg.read())
    
        # write the images to the xml library
        graphName = "image.jpg"
        path = 'output.image(%s)' % graphName
        lib.put(path + '.about.label', graphName)
        lib.put(path + '.current', jpgMIMEdata)

print lib.xml()

Back to Frequently Asked Questions

Last modified 10 years ago Last modified on Feb 21, 2014 3:25:19 PM