How to define an array based on Simulink simulation time?
Hello everyone, I’m attempting to define an array in a MATLAB Function block based on the simulation time in Simulink. In my code, I use ‘times index’ to record the number of simulation steps. I have set the time step to 0.01s.To achieve this goal, I used ‘persistent’ variables, but encountered an error. How can I implement my objective?
function [y,y1] = fcn(u)
persistent inputs; % 声明一个持久变量用于保存输入值
persistent time_index;
if isempty(inputs) % 如果持久变量为空,则初始化
inputs = u; % 将当前输入值保存到持久变量中
time_index = 1;
else
inputs = [inputs, u]; % 将当前输入值追加到持久变量中
time_index = time_index + 1;
end
% 计算平均值
mean_val = mean(inputs);
% 计算差值的平方
diff_squared = (inputs – mean_val).^2;
% 计算方差
y = sum(diff_squared) / length(inputs);
all_inputs(time_index) = u;
y1=all_inputs;
This is the error I encountered.Hello everyone, I’m attempting to define an array in a MATLAB Function block based on the simulation time in Simulink. In my code, I use ‘times index’ to record the number of simulation steps. I have set the time step to 0.01s.To achieve this goal, I used ‘persistent’ variables, but encountered an error. How can I implement my objective?
function [y,y1] = fcn(u)
persistent inputs; % 声明一个持久变量用于保存输入值
persistent time_index;
if isempty(inputs) % 如果持久变量为空,则初始化
inputs = u; % 将当前输入值保存到持久变量中
time_index = 1;
else
inputs = [inputs, u]; % 将当前输入值追加到持久变量中
time_index = time_index + 1;
end
% 计算平均值
mean_val = mean(inputs);
% 计算差值的平方
diff_squared = (inputs – mean_val).^2;
% 计算方差
y = sum(diff_squared) / length(inputs);
all_inputs(time_index) = u;
y1=all_inputs;
This is the error I encountered. Hello everyone, I’m attempting to define an array in a MATLAB Function block based on the simulation time in Simulink. In my code, I use ‘times index’ to record the number of simulation steps. I have set the time step to 0.01s.To achieve this goal, I used ‘persistent’ variables, but encountered an error. How can I implement my objective?
function [y,y1] = fcn(u)
persistent inputs; % 声明一个持久变量用于保存输入值
persistent time_index;
if isempty(inputs) % 如果持久变量为空,则初始化
inputs = u; % 将当前输入值保存到持久变量中
time_index = 1;
else
inputs = [inputs, u]; % 将当前输入值追加到持久变量中
time_index = time_index + 1;
end
% 计算平均值
mean_val = mean(inputs);
% 计算差值的平方
diff_squared = (inputs – mean_val).^2;
% 计算方差
y = sum(diff_squared) / length(inputs);
all_inputs(time_index) = u;
y1=all_inputs;
This is the error I encountered. simulink, matlab function, array define MATLAB Answers — New Questions