Running a MATLAB script in Python: "Operator '*' is not supported for operands of type 'cell'."
Mostrar comentarios más antiguos
I am trying to run a MATLAB script in Python to generate a trajectory for the Lorenz system. My Python code is:
import matlab.engine
eng = matlab.engine.start_matlab()
traj = eng.gen_lorenz([1, 1, 1],10,8/3,28,250,1/50)
eng.quit()
print(traj)
My MATLAB function is:
function [output] = gen_lorenz(init_pos,sigma,beta,rho,tf,dt)
%GEN_LORENZ
%Generates Lorenz Trajectory based on initial position (init_pos),
%sig/rho/beta values, every dt seconds to a final time (tf)
f = @(t,a) [-sigma*a(1) + sigma*a(2);
rho*a(1) - a(2) - a(1)*a(3);
-beta*a(3) + a(1)*a(2)];
[~,a] = ode45(f,[double(0):dt:double(tf)], init_pos);
output = a;
end
When I run the code, I keep getting the error "Operator '*' is not supported for operands of type 'cell'" on the line: f = @(t,a) ...
I'm assuming it's a problem with trajectory array (a) or the sig/beta/rho constants, but I'm not sure why they're being interpreted as a cells. The function works fine if it's run just on MATLAB.
Thanks
4 comentarios
Hanjin Liu
el 21 de Feb. de 2021
Hello.
Be sure that list objects in Python are converted to cells in matlab.engine so [1, 1, 1] is interpreted as a cell {1, 1, 1}.
You need to import matlab.double and the correct code will look like:
eng.gen_lorenz(matlab.double([1, 1, 1]), ...).
Max Van der Velden
el 21 de Feb. de 2021
Hanjin Liu
el 21 de Feb. de 2021
The following code worked well in my PC with a copy of your MATLAB function.
from matlab import double
traj = eng.gen_lorenz(double([1, 1, 1]),10.0,8/3,28.0,250.0,1/50)
You got a ValueError because matlab.double only takes arguments that are iterable.
matlab.double(10) ... error.
matlab.double([10]) ... works, but 10.0 is simpler because float in Python will be automatically converted to MATLAB double.
Max Van der Velden
el 21 de Feb. de 2021
Respuestas (0)
Categorías
Más información sobre Call MATLAB from Python en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!