1

Possible Duplicate:
Call Python function from MATLAB

I need to call a Python function from a MATLAB environment. Is it possible?

Let's assume, I have the following Python code:

def squared(x):
    y = x * x
    return y

How do I call squared(3) from MATLAB workspace/code and get 9?

1
  • Adrian suggested a method in : stackoverflow.com/questions/1707780/…. I tried it. I generated a squared.py code, saved it in C:\New, opened the perl.m file, replaced the word perl by python in the code, changed its name to python.m and saved it in C:\New. Matlab shows me the error command: ??? Error using ==> python at 82 System error: 'python' is not recognized as an internal or external command, operable program or batch file. Command executed: python squared.py 2 How can I fix it? Commented Jun 8, 2011 at 5:56

1 Answer 1

1

I have never done this before, so someone else will have to provide a 'real' answer, but I can offer this.

I often call the shell from MATLAB on my Linux machine, with an exclamation point, >>!{comm} So I suppose you could have a shell script that calls python and call the script from MATLAB.

wbg

Sign up to request clarification or add additional context in comments.

7 Comments

Just tried this and I can confirm it works. If you want to store the result in a variable, use something like x = evalc('!python hello.py')... You may have to specify a path for python since you're on a PC, not sure.
cool...never used evalc(), will look it up. I would put an in-line python function in () ?
I hadn't used it either, just looked it up to see how I could return arguments from the command line... I'm not sure what you mean by 'I would put an in-line function in ()'?
Hello wbg and Jeff, Thanks for your replies. Unfortunately, I still get error messages :S. I guess that I am making mistakes in providing path name. Can you be provide a more detailed description? If I save the squared function, i.e., the program written in the original post, in a code named squared.py, how can I call it from Matlab workspace?
@Nazmul I'm not sure, it works with just 'python' on a mac, but on a PC it's probably something like !c:\location\of\python.exe squared.py... Google ! for matlab
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.