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?

Community
  • 1
  • 1
Nazmul
  • 383
  • 3
  • 6
  • 17
  • Adrian suggested a method in : http://stackoverflow.com/questions/1707780/call-python-function-from-matlab. 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? – Nazmul Jun 08 '11 at 05:56

1 Answers1

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

wbg
  • 866
  • 3
  • 14
  • 34
  • 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. – Jeff Jun 08 '11 at 06:14
  • cool...never used evalc(), will look it up. I would put an in-line python function in () ? – wbg Jun 08 '11 at 06:38
  • 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 ()'? – Jeff Jun 08 '11 at 06:56
  • 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 Jun 08 '11 at 15:09
  • @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 – Jeff Jun 09 '11 at 02:38
  • I got it working! I saved the program in C:\Python27. I just added it in the python.m program. Thanks a lot to both of you! I appreciate your help. – Nazmul Jun 09 '11 at 20:04
  • great news....i was about to say, maybe the ! doesn't work on PC's....Consider learning Linux someday, I think it makes numerical programs easier. However, i realize that most work places use windows. – wbg Jun 12 '11 at 18:18