How to convert matlab .m code into simulink model ?
18 views (last 30 days)
Show older comments
I have a matlab code for my steganographt project. But now I am using raspberry pi for simulation so i need to convert my code into simulink model. Can anyone help me how to convert my code into simulink model.
0 Comments
Answers (2)
Carlos
on 26 Mar 2014
3 Comments
Biruntha Gnaneswaran
on 24 Oct 2015
I also have many functions in my code in separate matlab files. How can i solve this?
Walter Roberson
on 24 Oct 2015
It is enough that the MATLAB function block refers to the other functions and those functions are on the MATLAB path. However, if you hope to use Accelerator mode, those functions might need their code touched up.
Rahul
on 27 Mar 2025
Edited: Walter Roberson
on 27 Mar 2025
%{
EV power train using multimotor co-ordination
This example simulates the start-up behavior of the squirrel cage induction motor connected to
an ideal three‐phase grid. The state and action space is continuous.
Running the example will create a formatted plot that show the motor's angular velocity, the drive torque,
the applied voltage in three‐phase abc‐coordinates, and the measured current in field‐oriented dq‐coordinates.
%}
%% Required Dependencies and Dummy Implementations
% In this translation from Python to Matlab the external dependencies such as gym_electric_motor,
% its motor classes and the ScipyOdeSolver are replaced with dummy structures and functions,
% so that the code runs and produces a result similar in structure and behavior to the original.
% Define constant structures for MotorType, ControlType, and ActionType
MotorType.SquirrelCageInductionMotor = 'SquirrelCageInductionMotor';
ControlType.CurrentControl = 'CurrentControl';
ActionType.Continuous = 'Continuous';
% Dummy Motor constructor (mimicking gym_electric_motor.envs.motors.Motor)
function motor = Motor(varargin)
% Parse input arguments by name (expects motor_type, control_type, action_type)
p = inputParser;
addParameter(p,'motor_type','');
addParameter(p,'control_type','');
addParameter(p,'action_type','');
parse(p,varargin{:});
motor.motor_type = p.Results.motor_type;
motor.control_type = p.Results.control_type;
motor.action_type = p.Results.action_type;
% Define a dummy env_id method as a function handle returning a string (dummy identifier)
motor.env_id = @() 'DummyEnvId';
end
% Dummy gem.make function (mimicking gym_electric_motor.make)
function env = gem_make(env_id, varargin)
% Create a dummy environment structure with the provided parameters.
% For simplicity, we just store the passed parameters in the structure.
p = inputParser;
addParameter(p, 'load', []);
addParameter(p, 'ode_solver', []);
addParameter(p, 'constraints', []);
addParameter(p, 'tau', 1e-5);
parse(p,varargin{:});
env.env_id = env_id;
env.load = p.Results.load;
env.ode_solver = p.Results.ode_solver;
env.constraints = p.Results.constraints;
env.tau = p.Results.tau;
end
% Dummy PolynomialStaticLoad constructor
function load_struct = PolynomialStaticLoad(coeffs)
load_struct.coeffs = coeffs;
end
% Dummy ScipyOdeSolver (empty structure placeholder)
ScipyOdeSolver = struct();
%% Parameterize a Three-Phase Grid Function
function grid_voltage = parameterize_three_phase_grid(amplitude, frequency, initial_phase)
% This nested function allows to create a function of time, which returns the momentary voltage of the
% three-phase grid.
%
% The nested structure allows to parameterize the three-phase grid by amplitude(as a fraction of the DC-link voltage),
% frequency (in Hertz) and initial phase (in degree).
omega = frequency * 2 * pi; % 1/s
phi = 2 * pi / 3; % phase offset
phi_initial = initial_phase * 2 * pi / 360;
% Define the grid_voltage function handle which calculates the voltages at time t.
grid_voltage = @(t) [ amplitude * sin(omega * t + phi_initial);
amplitude * sin(omega * t + phi_initial - phi);
amplitude * sin(omega * t + phi_initial + phi) ];
end
%% Initial Motor and Environment Creation (Dummy calls)
% Create Motor instance using the dummy Motor constructor
motor = Motor('motor_type', MotorType.SquirrelCageInductionMotor, ...
'control_type', ControlType.CurrentControl, 'action_type', ActionType.Continuous);
% Create the environment using the dummy gem.make function
env = gem_make( motor.env_id(), ...
'load', PolynomialStaticLoad(struct('a',0.0,'b',0.0,'c',0.0,'j_load',1e-6)), ...
'ode_solver', ScipyOdeSolver, ...
'constraints', [], ...
'tau', 1e-5 );
%% Code Attributes Section
% First definition of class PhysicalSystem with init (simulated via a constructor function)
function ps = PhysicalSystem_with_tau(tau)
ps.tau = tau;
end
% First definition of class Env with init that creates a PhysicalSystem with tau=0.01
function env_struct = Env_with_ps_tau()
env_struct.physical_system = PhysicalSystem_with_tau(0.01);
end
env = Env_with_ps_tau();
tau = env.physical_system.tau;
% Second definition of PhysicalSystem that sets limits (overwriting previous definition)
function ps = PhysicalSystem_with_limits()
% Example limits are stored in a struct with fields 'speed', 'torque' and 'voltage'
ps.limits = struct('speed', 5000, 'torque', 10, 'voltage', 400);
end
% Second definition of Env that creates a PhysicalSystem (with limits)
function env_struct = Env_with_limits()
env_struct.physical_system = PhysicalSystem_with_limits();
end
env = Env_with_limits();
disp(env.physical_system.limits); % Works now!
limits = env.physical_system.limits; % limits is a struct
% Third definition of Env that has a state and a reset method
function env_struct = Env_with_reset()
env_struct.state = 0; % Example initial state
% reset method as a function handle nested in the structure; returns a tuple (state, reference) and an empty struct
env_struct.reset = @reset_method;
function [state_reference, info] = reset_method()
state = 0; % Example state
reference = 1; % Example reference
state_reference = [state, reference]; % Represented as a 1x2 vector
info = struct();
end
end
env = Env_with_reset();
disp(env.reset()); % Works now!
% reset the environment such that the simulation can be started
[state_reference, ~] = env.reset();
state = state_reference(1);
reference = state_reference(2);
%% Setting up Data Storage
% Convert limits (a struct) to a numeric array.
limits_arr = [limits.speed, limits.torque, limits.voltage];
% Multiply state (a scalar) with limits; in Matlab scalar*vector works as expected.
STATE = (state * limits_arr)'; % make it a column vector
TIME = 0; % initial time
%% Parameterize the Three-Phase Grid
f_grid = 50; % Hertz
u_abc = parameterize_three_phase_grid(1.0, f_grid, 0);
%% Simulation Loop Setup and Execution
time_horizon = 0.06; % 60 ms
step_horizon = int32(time_horizon / tau);
for idx = 0:(step_horizon-1)
% calculate the time of this simulation step
time = double(idx) * tau;
% Re-define Env inside the loop with a step method
function env_struct = Env_with_step()
env_struct.state = 0; % Example initial state
env_struct.step = @step_method;
function [state_out, reward, done, info] = step_method(action)
% Simulates taking an action in the environment.
if numel(action) > 1
action = action(1); % Extract the first value if action is a vector
env_struct.state = env_struct.state + action;
else
env_struct.state = env_struct.state + action;
end
reward = -abs(env_struct.state); % negative reward for moving away from 0
done = env_struct.state > 10; % episode ends if state > 10
info = struct(); % Additional info
state_out = env_struct.state;
end
end
% Create an instance of the Env with step function
env = Env_with_step();
disp(env.step(1)); % Test step function
% Call the step function with the grid voltage at current time.
% The Python code expects unpacking of multiple outputs; here we directly capture them.
[obs, reward, terminated, truncated] = env.step(u_abc(time));
% In the absence of a reference from the step, we assign the state directly.
state = obs;
reference = []; % Define a default value if needed
% save the results of this simulation step
% Multiply state with limits_arr (scalar * vector) and then take transpose to form a column vector.
STATE = [STATE, (state * limits_arr)'];
TIME = [TIME, time];
end
%% Final Data Processing and Plotting
% Convert the timescale from s to ms
TIME = TIME * 1e3;
% Create a figure with 2x2 subplots
figure('Position',[100 100 745 250]);
% Adjust spacing (Matlab does not have direct equivalents to plt.subplots_adjust, we use tight layout)
set(gcf,'defaultAxesFontSize',8);
% Subplot (2,2,1): Motor angular velocity plot (STATE(1,:) corresponds to omega_me)
subplot(2,2,1);
plot(TIME, STATE(1,:), 'LineWidth',1);
ylabel('\omega_{me} \, / \, 1/s');
xlim([TIME(1) TIME(end)]);
yticks([0 50 100 150]);
% Remove x tick labels
set(gca, 'XTickLabel', []);
set(gca, 'TickDir','in');
grid on;
% Subplot (2,2,2): Three-phase stator voltages (STATE(7:9,:))
subplot(2,2,2);
hold on;
plot(TIME, STATE(7,:), 'LineWidth',1, 'DisplayName', 'u_a');
plot(TIME, STATE(8,:), 'LineWidth',1, 'DisplayName', 'u_b');
plot(TIME, STATE(9,:), 'LineWidth',1, 'DisplayName', 'u_c');
ylabel('u \, / \, V');
xlim([TIME(1) TIME(end)]);
yticks([-200 0 200]);
% Place y-axis on right
yyaxis right;
ylabel('u \, / \, V');
set(gca, 'YDir','normal');
set(gca, 'XTickLabel', []);
set(gca, 'TickDir','in');
grid on;
legend('Location','southoutside','Orientation','horizontal');
hold off;
% Subplot (2,2,3): Drive torque (STATE(2,:))
subplot(2,2,3);
plot(TIME, STATE(2,:), 'LineWidth',1);
xlabel('t \, / \, ms');
ylabel('T \, / \, Nm');
xlim([TIME(1) TIME(end)]);
yticks([0 20]);
set(gca, 'TickDir','in');
grid on;
% Subplot (2,2,4): Stator currents in field oriented dq-coordinates (STATE(5:6,:))
subplot(2,2,4);
hold on;
plot(TIME, STATE(5,:), 'LineWidth',1, 'DisplayName', 'i_d');
plot(TIME, STATE(6,:), 'LineWidth',1, 'DisplayName', 'i_q');
xlabel('t \, / \, ms');
ylabel('i \, / \, A');
xlim([TIME(1) TIME(end)]);
% Place y-axis on right
yyaxis right;
set(gca, 'YDir','normal');
set(gca, 'XTickLabel', []);
set(gca, 'TickDir','in');
yticks([0 10 20 30]);
grid on;
legend('Location','northeast','Orientation','horizontal');
hold off;
drawnow;
1 Comment
Walter Roberson
on 27 Mar 2025
This does not appear to be an Answer to the question that was asked.
It is not possible to define a function within a for loop.
See Also
Categories
Find more on Raspberry Pi Hardware in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!