MATLAB Answers

How to pass the variables from matlab workspace to python function, and run this python function in matlab

64 views (last 30 days)
I am trying to pass the variables from matlab workspace to python function which scripting as:
def f():
global x,y
return x+y
and then I calling this python function in matlab command window by typing ' py.f.f' , however, the error occurred: Python Error: NameError: global name 'x' is not defined .
It would be much appreciated that if someone could help me to solve this, pass the variable from matlab to python function, and call the python function in matlab.

  0 Comments

Sign in to comment.

Accepted Answer

Robert Snoeberger
Robert Snoeberger on 1 Apr 2016
>> mod = py.importlib.import_module('f');
>> py.setattr(mod, 'x', 1);
>> py.setattr(mod, 'y', 2);
>> py.f.f
ans =
3
>>

  1 Comment

Pengfei Li
Pengfei Li on 11 Sep 2018
hello,
I want to pass the matlab data to python to create a csc sparse matrix using python language in matlab. now I met a problem, can you help me? I know you are an expert in this way, because I look many of you answers. Thank you very much. my code in matlab as follow, I met the data type problem.
iK=[0 2 2 0 1 2];
jK=[0 0 1 2 2 2];
sK=[1 2 3 4 5 6];
data=py.numpy.array(sK);
ir=py.numpy.array(iK);
jr=py.numpy.array(jK);
A = py.scipy.sparse.csc_matrix(data,ir,jr);
when I came to create the csc_matrix, then python would tell me the data type is not right. could you help me correct it? thank you very much.

Sign in to comment.

Sign in to answer this question.