How to execute Python script inside a Matlab '' for loop ''?

8 ビュー (過去 30 日間)
ABDUL VASIH T V 2020 年 2 月 16 日
コメント済み: Bo Li 2020 年 2 月 24 日
I have two Matlab " for loops " like this,
%Matlab Code:
for M=1:NoRun
for ii=1:NoP
z1 = position(ii,1,M);
z2 = position(ii,2,M);
And inside the second " for loop " I have a ' Python script ' with variables "z1" and "z2" like this,
#Python Code:
# Initialising the ANN
model0 = Sequential()
# Adding 1 hidden layer: the input layer and the first hidden layer
model0.add(Dense(units = z1, activation = 'tanh', input_dim = 4, kernel_initializer=my_init))
# Adding 2 hidden layer
model0.add(Dense(units = z2, activation = 'tanh', kernel_initializer=my_init))
# Adding output layer
model0.add(Dense(units = 6, activation = 'softmax', kernel_initializer=my_init))
# Set up Optimizer
Optimizer = tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.99)
# Compiling the ANN
model0.compile(optimizer = Optimizer, loss = 'categorical_crossentropy', metrics=['accuracy','categorical_crossentropy','mse'])
# Fitting the ANN to the Train set, at the same time observing quality on Valid set
history =, y_train_dummy, validation_data=(X_test, y_test_dummy), batch_size = 100, epochs = 1500)
# Generate prediction for all Train, Valid set and Experimental set
y_train_pred_model0 = model0.predict(X_train)
y_test_pred_model0 = model0.predict(X_test)
y_exp_pred_model0 = model0.predict(E_data)
# find final prediction by taking class with highest probability
y_train_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_train_pred_model0])
y_test_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_test_pred_model0])
y_exp_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_exp_pred_model0])
# check what metrics are in fact available in history
ac = (accuracy_score(y_test, y_test_pred_model0))*100
I need the value of accuracy_score 'ac' after each time executing the for loop, such that i can give this value to another variable inside this loop like this (written in Matlab)
%Matlab Cade:
if (pBestFF(ii)-IAE(M,ii))==0
pBestX(ii,:)=position(ii,:,M); %% Personal Best Particles
end % Second for loop ends here.
%% Global Best(gBest) Calculation
for ii=1:NoP
if (IAE(M,ii)-gBestFF)==0
% Calculation of Particle Velocity and Position
c1=2; c2=2;
inertia(M)=((NoRun - M)*(0.9 - 0.4))/NoRun + 0.4;
for ii=1:NoP
for jj=1:dimension
velocity(ii,jj,M+1) =inertia(M)* velocity(ii,jj,M) + c1*rand(1)*(pBestX(ii,jj) -
position(ii,jj,M)) + c2*rand(1)*(gBestX(jj) - position(ii,jj,M));%% Velocity update
velocity(ii,jj,M+1) = min(vmax(jj),max(vmin(jj),velocity(ii,jj,M+1)));
position(ii,jj,M+1) = position(ii,jj,M) + velocity(ii,jj,M+1);
gbestFF1=[gbestFF1 gBestFF];
Nrun1=[Nrun1 M];
end % First for loop ends here.
I am doing this in Matlab. Suggest your Ideas for how to do this in Matlab.

回答 (1 件)

Bo Li
Bo Li 2020 年 2 月 17 日
Hopefully I understand the question correctly. I wonder you can create a Python function in a Python file to wrap your Python script for example myFunc like following:
#myFunc accepts z1 and z2 as inputs, returns ac as output
def myFunc(z1, z2):
#Python logic
return ac
Then you MATLAB loops could look like following:
for M=1:NoRun
for ii=1:NoP
z1 = position(ii,1,M);
z2 = position(ii,2,M);
ac = py.mymodule.myFunc(z1, z2); should be in Python PATH or current folder
%use ac in more MATLAB logic
  4 件のコメント
Bo Li
Bo Li 2020 年 2 月 24 日
"how can I import Python script in matlab and pass the arguments (variables) to it and get the result from it, to pass the result to further Matlab Program"
%Say you create a Python file in folder "C:\work" and you have CPython 3.7 installed in "C:\python3" folder. You can launch MATLAB and do following in MATLAB:
>>cd c:\work
>>pyenv('Version', 'C:\python3\bin\python')
>>ac=py.mymodule.myFunc(1,2) %py.mymodule imports the Python module in MATLAB






Community Treasure Hunt

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

Start Hunting!

Translated by