I want to convert a recursive function to a iterative one. What I normally do is, I initialize a queue, put the first job into queue. Then in a while loop I consume
In the case where you need a queue only to store vectors (or scalars), then it is not difficult to use a matrix along with the circshift()
function to implement a basic queue with a fixed length.
% Set the parameters of our queue
n = 4; % length of each vector in queue
max_length = 5;
% Initialize a queue of length of nx1 vectors
queue = NaN*zeros(n, max_length);
queue_length = 0;
To push:
queue = circshift(queue, 1, 2); % Move each column to the right
queue(:,1) = rand(n, 1); % Add new vector to queue
queue_length = min(max_length, queue_length + 1);
To pop:
result = queue(:,last)
queue(:, last) = NaN;
queue_length = max(1, queue_length - 1);