Call Python from MATLAB
Main.MatlabCallsPython History
Hide minor edits - Show changes to output
Changed lines 42-43 from:
To use the Gekko package in Anaconda (and MATLAB), it must first be installed into the Anaconda package. The easiest way to do this is to open a new Jupyter Notebook session and install with
to:
To use the Gekko package in Anaconda (and MATLAB), it must first be installed into the Anaconda package. The easiest way to do this is to open a new Jupyter Notebook session and install with '''pip''' package manager.
Changed line 46 from:
to:
If there are not adminstrative privileges, the '''---user''' option can be added to install locally.
Changed lines 38-40 from:
{$3x+2y==1$}
{$x+2y==0$}
{$x+2y
to:
{$3x+2y=1$}
{$x+2y=0$}
{$x+2y=0$}
Changed line 1 from:
(:title Call Python Functions from MATLAB:)
to:
(:title Call Python from MATLAB:)
Changed line 8 from:
<iframe width="560" height="315" src="https://www.youtube.com/embed/videoseries?list=PLLBUgWXdTBDgeaeHTG8bpRmSS2fMCMRGg" frameborder="0" allowfullscreen></iframe>
to:
<iframe width="560" height="315" src="https://www.youtube.com/embed/aJGmnPfJBuo" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Changed lines 50-51 from:
MATLAB creates a new Gekko model with **m = py.gekko.GEKKO();** and then initializes new variables with statements such as **x = m.Var();**. Equations are defined with the variables and the double equal sign as **m.Equation(3*x+2*y==1);**. Finally, the problem is solved with **m.solve();** and the results are returned in **x.VALUE{1}** and **y.VALUE{1}**.
to:
MATLAB creates a new Gekko model with '''m = py.gekko.GEKKO();''' and then initializes new variables with statements such as '''x = m.Var();'''. Equations are defined with the variables and the double equal sign as '''m.Equation(3*x+2*y==1);'''. Finally, the problem is solved with '''m.solve();''' and the results are returned in '''x.VALUE{1}''' and '''y.VALUE{1}'''.
Changed line 77 from:
where **k** is a constant, **y** is the differential state, and **t** is time. Similar to the prior problem, MATLAB creates a new Gekko model with **m = py.gekko.GEKKO();** and then initializes the **y** variable with **y = m.Var(5.0);** with an initial condition of 5. The differential equation is defined with **m.Equation(k*y.dt()==-t*y);** and [[https://gekko.readthedocs.io/en/latest/imode.html|IMODE option]] is changed to dynamic simulation (4). Finally, the problem is solved with **m.solve();** and the results are returned in **y.VALUE.value**.
to:
where '''k''' is a constant, '''y''' is the differential state, and '''t''' is time. Similar to the prior problem, MATLAB creates a new Gekko model with '''m = py.gekko.GEKKO();''' and then initializes the '''y''' variable with '''y = m.Var(5.0);''' with an initial condition of 5. The differential equation is defined with '''m.Equation(k*y.dt()==-t*y);''' and [[https://gekko.readthedocs.io/en/latest/imode.html|IMODE option]] is changed to dynamic simulation (4). Finally, the problem is solved with '''m.solve();''' and the results are returned in '''y.VALUE.value'''.
Added lines 1-101:
(:title Call Python Functions from MATLAB:)
(:keywords function, Python, MATLAB, Numpy, Scipy, library, subroutine:)
(:description Access Python package functions from MATLAB. Three examples show how to use Numpy and Gekko functions to compute trigonometric functions, return values, solve linear equations, and solve a differential equation.:)
There are strengths to both MATLAB and Python. Using MATLAB functions in Python and Python functions in MATLAB are both possible. This tutorial shows how to use Python functions in a MATLAB script. In order to use Python in MATLAB, a Python installation must be available and the Python paths accessible. The easiest way to do this is to [[Main/PythonIntroduction|install Anaconda]] and launch MATLAB from the Anaconda prompt.
(:html:)
<iframe width="560" height="315" src="https://www.youtube.com/embed/videoseries?list=PLLBUgWXdTBDgeaeHTG8bpRmSS2fMCMRGg" frameborder="0" allowfullscreen></iframe>
(:htmlend:)
!!!! Exercise 1: Numpy in MATLAB
A first example uses the Numpy (Numerical Python) package in MATLAB to calculate the sine and cosine of values between 0 and 10. The values are computed with Numpy and then returned to MATLAB for plotting.
%width=500px%Attach:python_numpy_in_matlab.png
(:source lang=matlab:)
clear all
x = py.numpy.linspace(0,10,101);
y = py.numpy.sin(x);
z = py.numpy.cos(x);
xm = cellfun(@double,cell(x.tolist()));
ym = cellfun(@double,cell(y.tolist()));
zm = cellfun(@double,cell(z.tolist()));
plot(xm,ym,'b-')
hold on
plot(xm,zm,'r--')
legend('sin(x)','cos(x)')
(:sourceend:)
!!!! Exercise 2: Gekko Solves Linear Equations in MATLAB
A second example is the solution of two linear equations with Python Gekko in MATLAB.
{$3x+2y==1$}
{$x+2y==0$}
To use the Gekko package in Anaconda (and MATLAB), it must first be installed into the Anaconda package. The easiest way to do this is to open a new Jupyter Notebook session and install with
!pip install gekko
or if there are not adminstrative priviledges with:
!pip install --user gekko
MATLAB creates a new Gekko model with **m = py.gekko.GEKKO();** and then initializes new variables with statements such as **x = m.Var();**. Equations are defined with the variables and the double equal sign as **m.Equation(3*x+2*y==1);**. Finally, the problem is solved with **m.solve();** and the results are returned in **x.VALUE{1}** and **y.VALUE{1}**.
(:source lang=matlab:)
% start Matlab from Anaconda prompt
close all; clear;
% Solve linear equations
% Initialize Model
m = py.gekko.GEKKO();
% Initialize Variables
x = m.Var(); % define new variable
y = m.Var(); % default=0
% Define Equations
m.Equation(3*x+2*y==1);
m.Equation(x+2*y==0);
% Solve
m.solve();
% Extract values from Python lists using curly brackets
disp(['x: ' num2str(x.VALUE{1})]);
disp(['y: ' num2str(y.VALUE{1})]);
(:sourceend:)
!!!! Exercise 3: Gekko Solves ODE in MATLAB
A third example is the solution of an ordinary differential equation (ODE) with Python Gekko in MATLAB.
{$k\frac{dy}{dt}==-t y$}
where **k** is a constant, **y** is the differential state, and **t** is time. Similar to the prior problem, MATLAB creates a new Gekko model with **m = py.gekko.GEKKO();** and then initializes the **y** variable with **y = m.Var(5.0);** with an initial condition of 5. The differential equation is defined with **m.Equation(k*y.dt()==-t*y);** and [[https://gekko.readthedocs.io/en/latest/imode.html|IMODE option]] is changed to dynamic simulation (4). Finally, the problem is solved with **m.solve();** and the results are returned in **y.VALUE.value**.
(:source lang=matlab:)
% start Matlab from Anaconda prompt
close all; clear;
% Solve differential equation
m = py.gekko.GEKKO(pyargs('remote','False')); % Solve on local machine
m.time = py.numpy.linspace(0,20,100);
k = 10;
y = m.Var(5.0);
t = m.Param(m.time);
m.Equation(k*y.dt()==-t*y);
m.options.IMODE = 4;
m.solve()
% retrieving the values is a little more complicated here
time = cellfun(@double,cell(m.time.tolist()));
y = cellfun(@double,cell(y.VALUE.value));
plot(time,y)
xlabel('Time')
ylabel('y')
(:sourceend:)
Thanks to [[https://www.linkedin.com/in/abe-martin/|Abe Martin]] for generating the examples.
(:keywords function, Python, MATLAB, Numpy, Scipy, library, subroutine:)
(:description Access Python package functions from MATLAB. Three examples show how to use Numpy and Gekko functions to compute trigonometric functions, return values, solve linear equations, and solve a differential equation.:)
There are strengths to both MATLAB and Python. Using MATLAB functions in Python and Python functions in MATLAB are both possible. This tutorial shows how to use Python functions in a MATLAB script. In order to use Python in MATLAB, a Python installation must be available and the Python paths accessible. The easiest way to do this is to [[Main/PythonIntroduction|install Anaconda]] and launch MATLAB from the Anaconda prompt.
(:html:)
<iframe width="560" height="315" src="https://www.youtube.com/embed/videoseries?list=PLLBUgWXdTBDgeaeHTG8bpRmSS2fMCMRGg" frameborder="0" allowfullscreen></iframe>
(:htmlend:)
!!!! Exercise 1: Numpy in MATLAB
A first example uses the Numpy (Numerical Python) package in MATLAB to calculate the sine and cosine of values between 0 and 10. The values are computed with Numpy and then returned to MATLAB for plotting.
%width=500px%Attach:python_numpy_in_matlab.png
(:source lang=matlab:)
clear all
x = py.numpy.linspace(0,10,101);
y = py.numpy.sin(x);
z = py.numpy.cos(x);
xm = cellfun(@double,cell(x.tolist()));
ym = cellfun(@double,cell(y.tolist()));
zm = cellfun(@double,cell(z.tolist()));
plot(xm,ym,'b-')
hold on
plot(xm,zm,'r--')
legend('sin(x)','cos(x)')
(:sourceend:)
!!!! Exercise 2: Gekko Solves Linear Equations in MATLAB
A second example is the solution of two linear equations with Python Gekko in MATLAB.
{$3x+2y==1$}
{$x+2y==0$}
To use the Gekko package in Anaconda (and MATLAB), it must first be installed into the Anaconda package. The easiest way to do this is to open a new Jupyter Notebook session and install with
!pip install gekko
or if there are not adminstrative priviledges with:
!pip install --user gekko
MATLAB creates a new Gekko model with **m = py.gekko.GEKKO();** and then initializes new variables with statements such as **x = m.Var();**. Equations are defined with the variables and the double equal sign as **m.Equation(3*x+2*y==1);**. Finally, the problem is solved with **m.solve();** and the results are returned in **x.VALUE{1}** and **y.VALUE{1}**.
(:source lang=matlab:)
% start Matlab from Anaconda prompt
close all; clear;
% Solve linear equations
% Initialize Model
m = py.gekko.GEKKO();
% Initialize Variables
x = m.Var(); % define new variable
y = m.Var(); % default=0
% Define Equations
m.Equation(3*x+2*y==1);
m.Equation(x+2*y==0);
% Solve
m.solve();
% Extract values from Python lists using curly brackets
disp(['x: ' num2str(x.VALUE{1})]);
disp(['y: ' num2str(y.VALUE{1})]);
(:sourceend:)
!!!! Exercise 3: Gekko Solves ODE in MATLAB
A third example is the solution of an ordinary differential equation (ODE) with Python Gekko in MATLAB.
{$k\frac{dy}{dt}==-t y$}
where **k** is a constant, **y** is the differential state, and **t** is time. Similar to the prior problem, MATLAB creates a new Gekko model with **m = py.gekko.GEKKO();** and then initializes the **y** variable with **y = m.Var(5.0);** with an initial condition of 5. The differential equation is defined with **m.Equation(k*y.dt()==-t*y);** and [[https://gekko.readthedocs.io/en/latest/imode.html|IMODE option]] is changed to dynamic simulation (4). Finally, the problem is solved with **m.solve();** and the results are returned in **y.VALUE.value**.
(:source lang=matlab:)
% start Matlab from Anaconda prompt
close all; clear;
% Solve differential equation
m = py.gekko.GEKKO(pyargs('remote','False')); % Solve on local machine
m.time = py.numpy.linspace(0,20,100);
k = 10;
y = m.Var(5.0);
t = m.Param(m.time);
m.Equation(k*y.dt()==-t*y);
m.options.IMODE = 4;
m.solve()
% retrieving the values is a little more complicated here
time = cellfun(@double,cell(m.time.tolist()));
y = cellfun(@double,cell(y.VALUE.value));
plot(time,y)
xlabel('Time')
ylabel('y')
(:sourceend:)
Thanks to [[https://www.linkedin.com/in/abe-martin/|Abe Martin]] for generating the examples.