Is there a “queue” in MATLAB?

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

    1. Is a recursive solution really so bad? (always examine your design first).
    2. File Exchange is your friend. (steal with pride!)
    3. Why bother with the trouble of a proper Queue or a class - fake it a bit. Keep it simple:

    q = {};
    head = 1;
    q{head} = param;
    result = 0;
    while (head<=numel(q))
    %process param{head} and obtain new param(s) head = head + 1; %change result q{end+1} = param1; q{end+1} = param2; end %loop over q return result;

    If the performance suffers from adding at the end too much - add in chunks:

    chunkSize = 100;
    chunk = cell(1, chunkSize);
    q = chunk;
    head = 1;
    nextLoc = 2;
    q{head} = param;
    result = 0;
    while (head numel(q);
            q = [q chunk];
        end
        q{nextLoc} = param1;
        nextLoc = nextLoc + 1;
        q{end+1} = param2;
        nextLoc = nextLoc + 1;
    end %loop over q
     return result;
    

    A class is certainly more elegant and reusable - but fit the tool to the task.

提交回复
热议问题