我正在自学一些 python 和数学实验室的编程知识。我需要用 matlab 运行我在 python 中编写的几个函数。
我看到了这个例子: 在 python 中
import sys
def squared():
y=x*x
return y
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
然后在 matlab 中
[status,result]=system('nameofthescrip', 3)
status=0
result=9.0
但是,我不知道当我尝试使用我的函数时它不起作用。
我的程序是这样的:
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)
但是我不知道该用什么代替
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
以便我可以从 matlab 运行它,就像我首先编写的示例一样!
请您参考如下方法:
在你给出的例子中,代码
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
在脚本运行时运行,请参阅 SO answer .在您的情况下,您希望在脚本运行时运行的代码是
x=[function_1,function_2,function_3]
random.shuffle(x)
所以你应该把这段代码放在 if block 中:
if __name__ == '__main':
x=[function_1,function_2,function_3]
random.shuffle(x)
然后在 MATLAB 中,您可以用类似的方式调用 Python:
[status,result]=system('nameofthescript')
您的脚本没有输入,因此您不需要 MATLAB system 函数的第二个参数。确保你有正确的 shebang在脚本的顶部!
