필터 지우기
필터 지우기

How to add variables to the equation by using loop?

조회 수: 4 (최근 30일)
Rufat Ismayilov
Rufat Ismayilov 2021년 1월 26일
답변: Kautuk Raj 2024년 3월 25일
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?

답변 (1개)

Kautuk Raj
Kautuk Raj 2024년 3월 25일
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.

카테고리

Help CenterFile Exchange에서 Waveform Generation에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by