1

I have a .m file that is used to run a neural network in matlab, which I have locally installed on my computer. I am trying to write a python script that will loop through a list of possible transfer and training functions for the neural network multiple times. I've written a function to open and edit the .m file, but I don't know how to; 1. run the .m file from the python script 2. import the necessary data for the neural network as a space delimited matrix.

I have three data files that need to be imported as matrices, what would the code look like?

Neuronaut
  • 15
  • 4
  • 1
    Please show your code. – brandonscript Dec 25 '13 at 06:02
  • If you already have Matlab, and you actually need it to run the tests, why not just do the looping in Matlab? That said, you may be able to benefit from the [Sage interface to Matlab](http://sage.math.washington.edu/tmp/sage-2.8.12.alpha0/doc/ref/module-sage.interfaces.matlab.html) – chthonicdaemon Dec 25 '13 at 06:35
  • you can run matlab from python as you run any external binary. Use `-r` flag to run a script: `matlab -nojvm -nodisplay -nodesktop -r myScript` will start matlab as a console and run the m-file `myScript` - you only need to verify that `myScript` is in path. – Shai Dec 25 '13 at 08:22

1 Answers1

2

Code for the suggestion by Shai could look like this

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

your_dir   = '/path/to/your/mfile'
your_mfile = 'name_of_mfile_without.m'
logfile    = '/path/to/save/matlab/standard_out.txt'
# logfile  = '/dev/null'

transfer_functions = ['func_1','func_2']

for f in transfer_functions:
    os.system(' matlab -nodesktop -nosplash -nodisplay -r  \' '
              ' addpath ' + your_dir + ' ;                    '
              your_mfile + ' ' +  f  + ' ;                    '
              ' exit                     ;                 \' '
              '  > ' + logfile                                 )

The part between \' and \' is MATLAB code. This could help you to run your MATLAB code with input arguments. Uncomment logfile = '/dev/null', if you do not need the output in the logfile.

Community
  • 1
  • 1
BHF
  • 748
  • 7
  • 19
  • 1
    Just so you know, running matlab code using -r is problematic if stability is a concern. In case your matlab script encounters an error, Matlab will throw as usual, but then NOT return. This means that the spawned sub process will effectively hang. This can of course somewhat be solved with try catch in your script, but it is definetly not optimal in a production environment if that is what you need. There exist other ways of calling matlab through a binary interface... – KlausCPH Dec 25 '13 at 17:12