How do I import a data file as a matrix and run a .m file from a python script?

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?

 Accepted Answer

To run the .m file, use
matlab -nodisplay -r "try YourScriptName; catch me; end; quit"
where YourScriptName is the file name without the .m file.
To read the data from space-separated columns, you can load() it.

More Answers (2)

So is the code going to look like this, with the three files I have to load into matrices being NNinput, NNinputSiAvg340, NNoutput and the neural network file being NN_v1.m?
if true
import os
os.load('NNinput')
os.load('NNinputSiAvg340')
os.load('NNoutput')
matlab -nodisplay -r "try NN_v1; catch me; end; quit"
end

5 Comments

woops, I'm a bit new to this forum, so ignore that 'if true' and 'end' part lol
Inside NN_v1.m you would have
NNInput = load('NNinput');
NNinputSiAvg340 = load('NNinputSiAvg340');
NNoutput = load('NNoutput');
followed by configuring and training and whatever-else using those three matrices.
Okay, I put that into the NN_v1.m script, put when I run a python script with just the line
matlab -nodisplay -r "try NN_v1; catch me; end; quit"
Does it make a difference that I'm on linux? It probably does...I'm terribly sorry I didn't mention that before.
I have matlab2013a, located at /usr/local/MATLAB/R2013a/
No, that should work fine in Linux.
You can redirect output using the standard ">" redirection, if you want.
What are you seeing when you try this above ?

Sign in to comment.

Figured it out!
os.system("matlab -nodisplay < NN_v1.m")
Thanks for your help Walter!

1 Comment

Better would be
os.system("matlab -nodisplay -r 'try NN_v1; catch me; end; quit'")
When you redirect from a script, sometimes you end up with MATLAB endlessly asking for more input. And the try/catch/quit helps in case something goes wrong with the script.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!