nim*_*cap 21 queue matlab data-structures
我想将递归函数转换为迭代函数.我通常做的是,我初始化一个队列,把第一个作业放入队列.然后在while循环中,我从队列中消耗作业并将新的作业添加到队列中.如果我的递归函数多次调用自身(例如,走一棵树有很多分支),就会添加多个作业.伪代码:
queue = new Queue();
queue.put(param);
result = 0;
while (!queue.isEmpty()) {
param = queue.remove();
// process param and obtain new param(s)
// change result
queue.add(param1);
queue.add(param2);
}
return result;
Run Code Online (Sandbox Code Playgroud)
我在MATLAB中找不到任何类似结构的队列.我可以使用vector来模拟队列中添加3的队列:
a = [a 3]
Run Code Online (Sandbox Code Playgroud)
和删除元素是
val = a(1);
a(1) = [];
Run Code Online (Sandbox Code Playgroud)
如果我正确地使用MATLAB,这种方法将成为性能杀手.
在MATLAB中使用队列是否有理智的方法?
那么其他数据结构呢?
Amr*_*mro 33
如果您坚持使用正确的数据结构,可以在MATLAB中使用Java:
import java.util.LinkedList
q = LinkedList();
q.add('item1');
q.add(2);
q.add([3 3 3]);
item = q.remove();
q.add('item4');
Run Code Online (Sandbox Code Playgroud)
好的,这是一个使用MATLAB句柄类的快速,肮脏,几乎没有经过测试的实现.如果您只存储标量数值,则可以使用双数组作为"元素"而不是单元格数组.不知道表现.
classdef Queue < handle
properties ( Access = private )
elements
nextInsert
nextRemove
end
properties ( Dependent = true )
NumElements
end
methods
function obj = Queue
obj.elements = cell(1, 10);
obj.nextInsert = 1;
obj.nextRemove = 1;
end
function add( obj, el )
if obj.nextInsert == length( obj.elements )
obj.elements = [ obj.elements, cell( 1, length( obj.elements ) ) ];
end
obj.elements{obj.nextInsert} = el;
obj.nextInsert = obj.nextInsert + 1;
end
function el = remove( obj )
if obj.isEmpty()
error( 'Queue is empty' );
end
el = obj.elements{ obj.nextRemove };
obj.elements{ obj.nextRemove } = [];
obj.nextRemove = obj.nextRemove + 1;
% Trim "elements"
if obj.nextRemove > ( length( obj.elements ) / 2 )
ntrim = fix( length( obj.elements ) / 2 );
obj.elements = obj.elements( (ntrim+1):end );
obj.nextInsert = obj.nextInsert - ntrim;
obj.nextRemove = obj.nextRemove - ntrim;
end
end
function tf = isEmpty( obj )
tf = ( obj.nextRemove >= obj.nextInsert );
end
function n = get.NumElements( obj )
n = obj.nextInsert - obj.nextRemove;
end
end
end
Run Code Online (Sandbox Code Playgroud)
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;
如果性能受到最后添加太多的影响 - 添加块:
chunkSize = 100;
chunk = cell(1, chunkSize);
q = chunk;
head = 1;
nextLoc = 2;
q{head} = param;
result = 0;
while (head<endLoc)
%process param{head} and obtain new param(s)
head = head + 1;
%change result
if nextLoc > 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;
Run Code Online (Sandbox Code Playgroud)
一个类肯定更优雅和可重用 - 但适合任务的工具.