필터 지우기
필터 지우기

How to define an array based on Simulink simulation time?

조회 수: 3 (최근 30일)
guo qing
guo qing 2024년 6월 5일
댓글: guo qing 2024년 6월 5일
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.

답변 (1개)

Rishav
Rishav 2024년 6월 5일
Hi guo,
I understand that you are trying to initialize an array based on Simulink simulation time but encountering the 'Undefined function or variable "all_inputs"' error.
The issue here is that you are trying to use 'all_inputs' without declaring it as a 'persistent' variable, which would cause errors.
Just add the following line in your code:
persistent all_inputs;
  댓글 수: 2
guo qing
guo qing 2024년 6월 5일
Hello, thank you for your response. I wanted to ask why it is necessary to name it as a persistent variable. Are there any other ways to initialize an array based on time in Simulink?"
guo qing
guo qing 2024년 6월 5일
I tried the operation you suggested, but MATLAB requires me to initialize all_inputs using the if isempty command and it cannot be an empty array. Clearly, the size of the all_inputs array will change over time, for example, with changes in simulation time. Is there a good way to solve this problem, or do I have to

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by