# How to add variables to the equation by using loop?

5 visualizaciones (últimos 30 días)
Rufat Ismayilov el 26 de En. de 2021
Respondida: Kautuk Raj el 25 de Mzo. de 2024
How to write a loop to add variables to an equation in a loop if some indicator gets bigger every time?
For example:
sss(i,1) = ((y(i,1)-b(1,1)- b(2,1)*y(i-1,1)- b(3,1)*(y(i-1,1)-y(i-2,1)) - b(4,1)*(y(i-2,1)-y(i-3,1)))^2);
In this equation the lag (input variable) is 2 and therefore we have 4 'b' values. How to create a loop function for automatically adding extra b's when the lag(input variable) is increasing or removing b's when the lag is decreasing?
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Respuestas (1)

Kautuk Raj el 25 de Mzo. de 2024
Hello Rufat Ismayilov,
I see that you want to dynamically adjust the number of terms in an equation based on a specified lag variable.
To create a loop in MATLAB that automatically adjusts the number of terms in your equation based on the value of a lag variable, you can use a for loop to construct the summation of the b terms. Here is a general approach to do this:
% Define the lag input variable
lag = 2; % You can change this to increase or decrease the number of 'b' terms
% Define a column vector 'y' with random values for the sake of example
% The length of 'y' should be greater than the lag
n = 10; % Total number of observations in 'y'
y = rand(n, 1); % 'y' is a column vector with random values
% Define the 'b' vector with random coefficients
% The length of 'b' should be lag + 2
b = rand(lag + 2, 1);
% Preallocate the sss array for performance
sss = zeros(n, 1);
% Loop through the elements of y starting from the point where there is enough data to apply the lag
for i = (lag + 1):n
% Initialize the sum of b terms for the current i
b_sum = b(1,1);
% Loop through the lag terms and add them to the b_sum
for j = 1:lag
b_sum = b_sum + b(j+1,1) * (y(i-j+1,1) - y(i-j,1));
end
% Calculate the sss(i,1) according to the equation
sss(i,1) = ((y(i,1) - b_sum)^2);
end
% Display the result
disp(sss);
I hope this helps you with your question.
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Categorías

Más información sobre Waveform Generation en Help Center y File Exchange.

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by