take mean of consecutive 5 values.
    13 views (last 30 days)
  
       Show older comments
    
i want to fix the size of vector that is 5 ,then for every iteration calculate the value and perform mean of these 1to 5 values ,when 5 values is full,in the 6 iteration the mean of values from 2 to 6 and so on,if the mean is less than 0.1 then the iteration is stop.
U and V are the matrix having random values.
alpha=0.001;
for i=1:no_of_iteration       % no_of_iteration is some input value
    U=U-alpha*0.1;      % U is matrix ,randomly assign value
    V=V-alpha*0.1;      % V is matrix ,randomly assign value
    cost=sum(sum(U*V));
end
want to take the mean of 5 consecutive cost value ,and compare the value if less then 0.1 then stop iteration
0 Comments
Answers (1)
  BhaTTa
 on 10 Jun 2025
        Hey @RUCHI CHOUDHARY, To implement the moving average of cost values and stop the iteration when the mean drops below 0.1, you'll need to store the last 5 cost values in a vector and update it in a rolling fashion.
Please refer to the below code for reference:
alpha = 0.001;
no_of_iteration = 1000; % Or whatever your desired max iterations are
% Initialize U and V matrices (example: 3x3 matrices with random values)
U = rand(3);
V = rand(3);
cost_history = zeros(1, 5); % Initialize a vector to store the last 5 cost values
current_cost_index = 0; % To keep track of where to put the new cost
disp('Starting iterations...');
for i = 1:no_of_iteration
    U = U - alpha * 0.1;
    V = V - alpha * 0.1;
    cost = sum(sum(U * V));
    % Store the current cost in the history vector
    current_cost_index = mod(i - 1, 5) + 1; % This makes it a circular buffer (1, 2, 3, 4, 5, 1, 2, ...)
    cost_history(current_cost_index) = cost;
    % Only calculate and check the mean if we have at least 5 cost values
    if i >= 5
        current_mean_cost = mean(cost_history);
        fprintf('Iteration %d: Current Cost = %.4f, Moving Mean (last 5) = %.4f\n', i, cost, current_mean_cost);
        if current_mean_cost < 0.1
            disp('Moving mean of cost is less than 0.1. Stopping iterations.');
            break; % Exit the loop
        end
    else
        fprintf('Iteration %d: Current Cost = %.4f (Collecting 5 values for mean)\n', i, cost);
    end
end
disp('Loop finished.');
% You can check the final U, V, and cost_history here if needed
0 Comments
See Also
Categories
				Find more on Creating and Concatenating Matrices in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
