Is there a “queue” in MATLAB?

后端 未结 7 1919
温柔的废话
温柔的废话 2020-12-28 16:14

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

7条回答
  •  無奈伤痛
    2020-12-28 16:45

    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);
    

提交回复
热议问题