Implementing a shift register into a Matlab function

46 vues (au cours des 30 derniers jours)
AN
AN le 30 Nov 2020
Modifié(e) : AN le 1 Déc 2020
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?

Réponse acceptée

Ameer Hamza
Ameer Hamza le 30 Nov 2020
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 commentaires
AN
AN le 1 Déc 2020
Modifié(e) : AN le 1 Déc 2020
All right, this works perfectly. Thank you so much for your help!
Ameer Hamza
Ameer Hamza le 1 Déc 2020
I am glad to be of help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Simulink Environment Customization dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by