Why are my graphs closing when I use the matlab api?

7 ビュー (過去 30 日間)
Josh Cohenour
Josh Cohenour 2017 年 6 月 19 日
編集済み: Frederik 2024 年 9 月 27 日
I'm having an issue where I run this code in my matlab python api and the graph closes right after all the assets load onto the graph and can't seem to figure out why, I'll leave an example I found that does exactly what i was saying. Any help would be very much appreciated.
import matlab.engine
eng = matlab.engine.start_matlab()
eng.eval("T = readtable('patients.dat');",nargout=0)
eng.eval("S = table2struct(T,'ToScalar',true);",nargout=0)
eng.eval("disp(S)",nargout=0)
D = eng.workspace["S"]
smoker = matlab.logical(D["Smoker"])
pressure = D["Diastolic"]
pressure.reshape((1,100))
pressure = pressure[0]
smoker.reshape((1,100))
smoker = smoker[0]
sp = [p for (p,s) in zip(pressure,smoker) if s is True]
nsp = [p for (p,s) in zip(pressure,smoker) if s is False]
print(len(sp))
print(len(nsp))
sp = matlab.double(sp)
nsp = matlab.double(nsp)
print(eng.mean(sp))
print(eng.mean(nsp))
sdx = eng.linspace(1.0,34.0,34)
nsdx = eng.linspace(1.0,34.0,66)
eng.figure(nargout=0)
eng.hold("on",nargout=0)
eng.box("on",nargout=0)
eng.scatter(sdx,sp,10,'blue')
h = eng.scatter(nsdx,nsp,10,'red')
h = eng.xlabel("Patient (Anonymized)")
h = eng.ylabel("Diastolic Blood Pressure (mm Hg)")
h = eng.title("Blood Pressure Readings for All Patients")
h = eng.legend("Smokers","Nonsmokers")
x = matlab.double([0,35])
y = matlab.double([89.9,89.9])
h = eng.line(x,y,"Color","blue")
h = eng.text(21.0,88.5,"89.9 (Smoker avg.)","Color","blue")
y = matlab.double([79.4,79.4])
h = eng.line(x,y,"Color","red")
h = eng.text(5.0,81.0,"79.4 (Nonsmoker avg.)","Color","red")code

回答 (1 件)

Robert Snoeberger
Robert Snoeberger 2017 年 6 月 22 日
My guess is that MATLAB is exiting when your script finishes. Since you are starting a new MATLAB session, the lifetime of MATLAB is tied to the lifetime of the variable 'eng'. You could consider using a shared MATLAB [1].
  3 件のコメント
Tianya Duan
Tianya Duan 2020 年 3 月 25 日
Thank you for your answer, help me a lot.
Frederik
Frederik 2024 年 9 月 27 日
編集済み: Frederik 2024 年 9 月 27 日
This trick helped me too.
Just as little addition; if you call this isvalid(h) right after the code above, it will check for the validity of a line object. It would make a little more sense to check for the validity of a figure handle. Therfore... replace eng.figure(nargout=0) by fh = eng.figure(nargout=0) and check with isvalid(fh)...
thanks a lot

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCall MATLAB from Python についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by