How to convert python code to Matlab?

338 次查看(过去 30 天)
Is there way to convert this python code to matlab code?
how can i convert python code to matlab???
this is the code that I want to convert:
import os
os.environ("KMP_DUPLICATE_LIB_OK") = "TRUE"; %%aggiungo una variabile ambiente
from sklearn.cluster import estimate_bandwidth
from sklearn import metrics
def estimate_bandwidth_meanshift(features, perc, quantile=0.5):
print('Start estimating bandwidth -------------------------------------')
bandwidth = estimate_bandwidth(features, quantile=quantile, n_samples = int(features.shape(0)*perc/100))
print('End estimating bandwidth ---------------------------------------')
return bandwidth
def getNMI(prediction, gt):
return metrics.normalized_mutual_info_score(gt, prediction)
def getARI(prediction, gt):
return metrics.adjusted_rand_score(gt, prediction)
  3 个评论
filippo gistri
filippo gistri 2022-11-11
I tried to run python on matlab, but it didn't work.
If i run, matlab return this error:
Error using python_utility><module>
Error in <frozen importlib>_call_with_frames_removed (line 241)
Error in <frozen importlib>exec_module (line 883)
Error in <frozen importlib>_load_unlocked (line 688)
Error in <frozen importlib>_find_and_load_unlocked (line 1006)
Error in <frozen importlib>_find_and_load (line 1027)
Error in <frozen importlib>_gcd_import (line 1050)
Error in __init__>import_module (line 126)
Rik
Rik 2022-11-11
I don't work with the Python link enough to understand this error without seeing the code you tried.

请先登录,再进行评论。

采纳的回答

Aditya Jha
Aditya Jha 2022-11-16
Hi!
There is no direct way to convert python code to MATLAB.
There are two approaches:
Refer to the following MATLAB answers post with similar issue:

更多回答(4 个)

rushabh rupani
rushabh rupani 2023-1-28
Converting Python code to Matlab can be a complex process, as the two languages have different syntax and libraries.
You can use the Py2Mat library to accomplish your desired result.

Lekkalapudi Chandini
% Plot the displacement versus time
plot(t, x(:, 1))
xlabel('Time (s)')
ylabel('Displacement (m)')
title('Displacement of Mechanical System')

Anoy Chowdhury
Anoy Chowdhury 2023-7-20
Only some commands like
py.list({'This','is a','list'})
are recommendable to use from python. In the other hand, you can create a full funcion in python script / function and call it with:
pyrun('my_python_callback')
However, trying to "convert" a python script line by line to MATLAB is pointless. To give you a context, is equivalent to try to convert to python some script which includes:
%...
sys = armax(tt2,[na nb nc nk])
%...
Since armax belongs to a toolbox (System Identification) it would be extremely complicated and unpractical.
If you want to use a python library as sklearn.cluster, stay in python, the only reason to import to MATLAB should be importing a python environment to interact with an MATLAB , for example an MATLAB AI agent:
classdef mountain_car_1 < rl.env.MATLABEnvironment
properties
open_env = py.gym.make('MountainCar-v0'); %% IMPORT PYTHON OPEN AI ENVIRONMENT
end
methods
function this = mountain_car_1()
ObservationInfo = rlNumericSpec([2 1]);
ObservationInfo.Name = 'MountainCar Descreet';
ObservationInfo.Description = 'Position, Velocity';
ActionInfo = rlFiniteSetSpec([0 1 2]);
ActionInfo.Name = 'Acceleration direction';
this = this@rl.env.MATLABEnvironment(ObservationInfo,ActionInfo);
end
function [Observation,Reward,IsDone,LoggedSignals] = step(this,Action)
result = cell(this.open_env.step(int16(Action)));
Observation = double(result{1})';
Reward = double(result{2});
IsDone = double(result{3});
LoggedSignals = [];
if (Observation(1)>=0.4)
Reward = 0;
IsDone = 1;
end
end
function InitialObservation = reset(this)
result = this.open_env.reset();
InitialObservation = double(result)';
end
end
end
In the previous example, if you had installed Python 3.10, and OpenAIGym, you can import the desired environment to MATLAB and interact both with the used and a potencial AI Bot.

Yerisn
Yerisn 2024-6-19
import numpy as np
# Paso 1: Definir parámetros geométricos y mecánicos
E = 200000 # Módulo elástico en MPa
alpha = 12e-6 # Coeficiente de dilatación térmica en 1/°C
delta_T = -20 # Diferencia de temperatura por enfriamiento en °C
A1 = 6000 # Área de la barra 1 en mm^2
A2 = 5000 # Área de la barra 2 en mm^2
A3 = 4000 # Área de la barra 3 en mm^2
L1 = 6000 # Longitud de la barra 1 en mm
L2 = 8000 # Longitud de la barra 2 en mm
L3 = 5000 # Longitud de la barra 3 en mm
angles = [-np.pi/2, 5 * np.pi / 6, np.pi / 4] # Ángulos en radianes
# Paso 2: Definir la tabla de conectividades
connectivity = np.array([[1, 2], [1, 4], [1, 3]]) # Nodos
dof_connectivity = np.array([[0, 1, 2, 3], [0, 1, 6, 7], [0, 1, 4, 5]]) # Grados de libertad
print("Tabla de conectividades")
print(connectivity.reshape((3, 2)))
print(dof_connectivity.reshape((3, 4)))
# Paso 3: Definir las matrices de rigidez elementales referidas a los sistemas de referencia locales
k1_local = (E * A1 / L1) * np.array([[1, -1], [-1, 1]])
k2_local = (E * A2 / L2) * np.array([[1, -1], [-1, 1]])
k3_local = (E * A3 / L3) * np.array([[1, -1], [-1, 1]])
print("Matrices de rigidez elementales referidas a los sistemas de referencia locales")
print(k1_local)
print(k2_local)
print(k3_local)
# Paso 4: Definir los vectores de cargas elementales (por temperatura y rigidez) referida a los sistemas de referencia locales
f_T1 = np.array([-alpha * delta_T * E * A1, alpha * delta_T * E * A1])
f_T2 = np.array([-alpha * delta_T * E * A2, alpha * delta_T * E * A2])
f_T3 = np.array([-alpha * delta_T * E * A3, alpha * delta_T * E * A3])
print("Vectores de cargas elementales")
print(f_T1)
print(f_T2)
print(f_T3)
# Paso 5: Definir las matrices de rotación de cada barra
def rotation_matrix(angle):
c = np.cos(angle)
s = np.sin(angle)
return np.array([[c, s, 0, 0], [0, 0, c, s]])
R1 = rotation_matrix(angles[0]) # Barra 1 (ángulo de -π/2 radianes)
R2 = rotation_matrix(angles[1]) # Barra 2 (ángulo de 5π/6 radianes)
R3 = rotation_matrix(angles[2]) # Barra 3 (ángulo de π/4 radianes)
print("Matrices de rotación de cada barra")
print(R1)
print(R2)
print(R3)
# Paso 6: Transformar las matrices de rigidez del sistema de referencia local al sistema de referencia global
k1_global = R1.T @ k1_local @ R1
k2_global = R2.T @ k2_local @ R2
k3_global = R3.T @ k3_local @ R3
print("Transformación de las matrices de rigidez del sistema de referencia local al sistema de referencia global")
print(k1_global)
print(k2_global)
print(k3_global)
# Paso 7: Transformar los vectores de carga del sistema de referencia local al sistema de referencia global
F_T1_global = R1.T @ f_T1
F_T2_global = R2.T @ f_T2
F_T3_global = R3.T @ f_T3
print("Transformación de los vectores de carga del sistema de referencia local al sistema de referencia global")
print(F_T1_global)
print(F_T2_global)
print(F_T3_global)
# Paso 8: Ensamblar la matriz de rigidez global (8x8)
K_global = np.zeros((8, 8))
# Contribución de la barra 1 (nodo 1 a nodo 2)
K_global[np.ix_([0, 1, 2, 3], [0, 1, 2, 3])] += k1_global
# Contribución de la barra 2 (nodo 1 a nodo 4)
K_global[np.ix_([0, 1, 6, 7], [0, 1, 6, 7])] += k2_global
# Contribución de la barra 3 (nodo 1 a nodo 3)
K_global[np.ix_([0, 1, 4, 5], [0, 1, 4, 5])] += k3_global
print("Matriz de rigidez global")
print(K_global)
# Paso 9: Ensamblar el vector de carga global
F_global = np.zeros(8)
F_global[0:2] += F_T1_global[:2]
F_global[0:2] += F_T2_global[:2]
F_global[0:2] += F_T3_global[:2]
print("Vector de carga global")
print(F_global)
# Condiciones de contorno: nodos 2, 3 y 4 son empotrados (desplazamientos = 0)
fixed_dofs = [2, 3, 4, 5, 6, 7]
free_dofs = [0, 1]
# Reducción de la matriz de rigidez y el vector de fuerzas
K_reduced = K_global[np.ix_(free_dofs, free_dofs)]
F_reduced = F_global[free_dofs]
# Paso 10: Resolver las incógnitas
# a) Desplazamiento del nodo central 1
displacements = np.linalg.solve(K_reduced, F_reduced)
# Vector de desplazamientos completo
displacement_vector = np.zeros(8)
displacement_vector[free_dofs] = displacements
# b) Calcular las reacciones de vínculo en los empotramientos
reactions = K_global @ displacement_vector - F_global
# c) Calcular deformaciones y tensiones en cada barra
deformation_1 = (displacement_vector[1] - displacement_vector[0]) / L1
deformation_2 = (displacement_vector[7] - displacement_vector[6]) / L2
deformation_3 = (displacement_vector[5] - displacement_vector[4]) / L3
stress_1 = E * deformation_1
stress_2 = E * deformation_2
stress_3 = E * deformation_3
# Resultados en formato de matrices
print("Desplazamiento del nodo central 1 (x, y):")
print(displacements.reshape((2, 1)))
print("Reacciones de vínculo en los empotramientos:")
print(reactions.reshape((8, 1)))
print("Deformaciones en cada barra (1, 2, 3):")
print(np.array([deformation_1, deformation_2, deformation_3]).reshape((3, 1)))
print("Tensiones en cada barra (1, 2, 3):")
print(np.array([stress_1, stress_2, stress_3]).reshape((3, 1)))
convierte a codigo matlab

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by