Implementing a shift register into a Matlab function

Hello everyone,
I'm trying to write a shift register in a MATLAB-Function in Simulink. So I have an initial Matrix M, that is supposed to change for every new Input-value of L in Simulink in a way that it saves the new input value as it's first value and pushes the other values one step back and deletes the last value.
For better explanation: If this wasn't a function, but a calculation in a loop, the working code would look like this:
M=[1; 2; 3; 4; 5];
L=[10;20;30;40;50];
for x=1:5
M=[L(x); M(1:end-1)];
end
However I want to use real- time data in the end, so this doesn't work for me.
This is what I have so far (it's a Matlab-Function in Simulink):
function y = fcn(L, M)
M=[L ; M(1:end-1)];
y = mean(M);
When I run this, it just overwrites the first value in M and doesn't push the other values back. Can anybody help?

 采纳的回答

To save a variable between different iterations of MATLAB function block in Simulink, declare it as persistent. For example, if the initial value of M is given, you can do something like this
function y = fcn(L)
persistent M
if isempty(M)
M = [1; 2; 3; 4; 5];
end
M = [L; M(1:end-1)];
y = mean(M);

4 个评论

First of all: thank you for your reply!
However M is a vector from the Simulink-workspace and only supposed to define the very beginning of my function. It is then supposed to change in the way that every new value of L that I put into the function gets written into the first part of M and the other values of M get pushed back. For example:
  • beginning: M=[1 2 3 4 5]
  • at time t=1 sec first value is L=10, so M is supposed to be: M=[10 1 2 3 4]
  • then at t=2 sec the value is L=20, so M is: M=[20 10 1 2 3]
  • t=3 s value L=30, so M is: M=[30 20 10 1 2]
and so on. I hope my goal is a bit clearer now?
Ok, If M must be an input to the MATLAB function block, then you change it from inside the function block. Simulink will reset its value at each iteration. You can try something like this
function y = fcn(L, M)
persistent M_
if isempty(M_)
M_ = M;
end
M_ = [L; M_(1:end-1)];
y = mean(M_);
All right, this works perfectly. Thank you so much for your help!

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Simulink 的更多信息

产品

版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by