I'm teaching myself a little bit of programming in python and also mathlab. And I need to run a couple of functions I wrote in python with matlab.
I saw this example: In python
import sys
def squared():
y=x*x
return y
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
then in matlab
[status,result]=system('nameofthescrip', 3)
status=0
result=9.0
but, I don't know when I try with my functions it doesn't work.
my program goes something like this:
def function_1():
Shows something on screen
return
def function_2():
hear a sound
return
def function_3():
write a number and press a key
return
x=[function_1,funciotion_2,function_3]
random.shuffle(x)
But then I don't know what to put inestead of
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
So that I can run it from matlab, just as the example I wrote first!
2 Answers 2
In the example you give, the code
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
is run when the script is run, see this SO answer. In your case, the code you want to run when the script is run is
x=[function_1,function_2,function_3]
random.shuffle(x)
so you should put that code inside the if block:
if __name__ == '__main':
x=[function_1,function_2,function_3]
random.shuffle(x)
Then in MATLAB you can invoke the Python in a similar way:
[status,result]=system('nameofthescript')
There is no input to your script, so you don't need the second argument of the MATLAB system function. Make sure you have the correct shebang at the top of your script!
1 Comment
Note that random.shuffle(x) will just rearrange the list x, it won't run or return anything, so your script isn't going to output anything. If you want to run the functions, you'll have to add something like
for f in x:
f()
to the end of your code, and this will loop through the (shuffled) list of functions and then run each one in that (random) order.
If any of your functions include print, then you should see the results. If you don't, you can try replacing any print with the sys.std.write function you see in the example.
You don't even need the if __name__=='__main__' line unless you want to import your file but not run that part at the end.