Is there a “queue” in MATLAB?

后端 未结 7 1821
温柔的废话
温柔的废话 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:48

    I had a need for queue like data structure as well.

    Fortunately I had a limited number of elements (n).

    They all get into queue at some point but only once.

    If you situation is similar you can adapt the simple algorithm using fixed size array and 2 indices.

    queue  = zeros( n, 1 );
    firstq = 1;
    lastq  = 1;
    
    while( lastq >= firstq && firstq <= n )
        i = queue( firstq );    % pull first element from the queue
                                % you do not physically remove it from an array,
                                % thus saving time on memory access
        firstq = firstq + 1;
    
        % % % % % % % % % % % % % WORKER PART HERE
        % do stuff
    
        %
        % % % % % % % % % % % % % % % % % % % % %
    
        queue( lastq ) = j;     % push element to the end of the queue
        lastq = lastq + 1;      % increment index
    
    end;
    

提交回复
热议问题