Running a python script in matlab

조회 수: 90 (최근 30일)
Tom Leblicq
Tom Leblicq 2013년 1월 15일
댓글: M Al Mamun 2021년 10월 14일
Hi, I tried to run a python script in matlab. I used the function system.So fa so good.
The pyhton script uses two input variables. In matlab I can enter one and then it runs without problems but when I try to enter two separate variables I always get an error.
systemCommand = ['python sqd.py ',num2str(a),num2str(omtrek)]
[status, result] = system(systemCommand);
This is the error:
status =
1
result =
Traceback (most recent call last):
File "sqd.py", line 10, in <module>
sys.stdout.write(str(squared(x)))
TypeError: squared() takes exactly 2 arguments (1 given)
Can someone help me?
Thanks!
  댓글 수: 1
Charles
Charles 2017년 8월 29일
This is interesting I am new to python, and I am trying to to do the dame thing Does the solution in fact work? I am keen to try it. I literally do not know python at all, neither am I am a programmer but I find it all fascinating and I move forward by trail and error. Some how I make progress. I will try this, but what infrastructure do you have? I have Matlab, 2017a and Python 3.6 Do i need anything else? I am reading that the former does not support the latter. Any thoughts?

댓글을 달려면 로그인하십시오.

채택된 답변

Friedrich
Friedrich 2013년 1월 16일
편집: Friedrich 2013년 1월 16일
Hi,
when modifying your script to:
import sys
def squared(a,omtrek):
b = (omtrek/2)-a
return b
if __name__ == '__main__':
x = float(sys.argv[1])
y = float(sys.argv[2])
sys.stdout.write(str(squared(x,y)))
and calling it from MATLAB:
>>!C:\Python32\python.exe sqd.py 1 2
it works fine for me. Or in your way:
>> a = 1
>> omtrek = 2
>>systemCommand = ['C:\Python32\python.exe sqd.py ',num2str(a),' ',num2str(omtrek)]
>> system(systemCommand)
0.0
ans =
0
  댓글 수: 1
Aravind Sasikumar
Aravind Sasikumar 2016년 4월 18일
편집: Aravind Sasikumar 2016년 4월 18일
Hello, The above code works for me too. The program is running but I am not able to get back the value of b in Matlab. I want to perform further calculations with the value of b.
import sys
def add(a,c):
b=a+c
return b
if _name_ == 'main':
x=float(sys.argv[1])
y=float(sys.argv[2])
sys.stdout.write(str(add(x,y)))
Why am I not getting the value of b back in matlab ?

댓글을 달려면 로그인하십시오.

추가 답변 (7개)

Bo Li
Bo Li 2016년 4월 18일
Why not using Python Interface?
The MATLAB statement can be as simple as following:
>> b=py.sqd.squared(10,30)
  댓글 수: 1
M Al Mamun
M Al Mamun 2021년 10월 14일
This is easy to apply and works perfectly.

댓글을 달려면 로그인하십시오.


Shashank Prasanna
Shashank Prasanna 2013년 1월 15일
Could you try the above with a space between the two arguments?
systemCommand = ['python sqd.py ',num2str(a),' ',num2str(omtrek)]

Tom Leblicq
Tom Leblicq 2013년 1월 16일
This is the python script:
import sys
def squared(a,omtrek):
b = (omtrek/2)-a
return b
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
It's very easy code, but this is just a test for a more complex program I would like to run.
In python it works. In Matlab it doesn't. It's true that the code needs two inputs. But my question is how can I give two inputs using matlab?

Tom Leblicq
Tom Leblicq 2013년 1월 16일
You are right Friedrich, this works! Thanks!
But by doing this I have another problem. The python code calculates the value of a parameter "b". I need this parameter in matlab for further processing. The correct value appears on my screen but I can't handle it. For example like this:
2.0>>

Aysha Ashraf
Aysha Ashraf 2017년 12월 21일
Can any one help me how to integrate this python code to matlab, i want to run this python program in matlab...
#Load dependencies import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from matplotlib import* import matplotlib.pyplot as plt from matplotlib.cm import register_cmap from matplotlib.mlab import PCA from sklearn.decomposition import PCA
from scipy import stats #from wpca import PCA from sklearn.decomposition import PCA as sklearnPCA import seaborn
#Load movie names and movie ratings movies = pd.read_csv('movies.csv') ratings = pd.read_csv('ratings.csv') ratings.drop(['timestamp'], axis=1, inplace=True) # def replace_name(x): return movies[movies['movieId']==x].title.values[0] # ratings.movieId = ratings.movieId.map(replace_name) # M = ratings.pivot_table(index=['userId'], columns=['movieId'], values='rating') m = M.shape #posesall = pd.read_csv('FileName_Poses.csv') df1 = M.replace(np.nan, 0, regex=True) X_std = StandardScaler().fit_transform(movies) #Step 2: Covariance Matrix and Eigendecomposition mean_vec = np.mean(X_std, axis=0) cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1) print('Covariance matrix \n%s' %cov_mat) print('NumPy covariance matrix: \n%s' %np.cov(X_std.T)) #Perform eigendecomposition on covariance matrix cov_mat = np.cov(X_std.T) eig_vals, eig_vecs = np.linalg.eig(cov_mat) print('Eigenvectors \n%s' %eig_vecs) print('\nEigenvalues \n%s' %eig_vals) # Step 3: Selecting Principal Components # Visually confirm that the list is correctly sorted by decreasing eigenvalues eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))] print('Eigenvalues in descending order:') for i in eig_pairs: print(i[0]) pca = PCA(n_components = 93) All_poses_pca = pca.fit_transform(movies) Variance = (pca.explained_variance_ratio_)
#Explained variance pca = PCA().fit(X_std) plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.title('Scree Plot') plt.xlabel('Number of principal components') plt.ylabel('Cumulative explained variance') plt.show()

Yodish
Yodish 2018년 4월 12일
It works for me as well, but it is very slow. It takes 0.2 sec to call a sum function from Python
Any ideas on how to speed it up? Where is the bottle neck?

Agapi Dav
Agapi Dav 2018년 7월 31일
Hello everyone! I have some images read in matlab and I want to process them in python and them return them to matlab for further processing.
Everything with the systemCommand works, however, even though I can import variables from matlab to python, because they are already in the workspace, I cannot return variables (e.g. images) back to matlab, when running the python script. Till now, in order to make it work, I save the python-processed images and then read them again from matlab.
I would like to ask if there is a more efficient way. In other words, in the example of Tom Leblicq, I would like to return the parameter b in matlab for further processing.
Thank you in advance!
  댓글 수: 1
Abdelwahab Afifi
Abdelwahab Afifi 2021년 1월 12일
The following command will return b in the workspace of MATLAB
b=py.sqd.squared(2)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by